skip to Main Content

Need to split array value and compare it to with another splited array value.
For eg

{
    "Info": [
        "A;35;Jan 20 2023;",
        "B;45;Feb 20 2013"
    ]
}

Want to compare both dates and get 2nd parameter(35 value )of latest date.
Array size is variable.

Please help how to get value of latest date.

Thank you.

Try to get value from array 2

2

Answers


  1. From your question I guess that you have an array where the first and second item are dependent on each other, then the third and fourth etc…

    In that case you could make every two elements into a mini-array which would help when you run comparisons between the two values in each mini-array.

    But the question isn’t crystal clear on this so I am guessing 🙂

    let arr = ['Tom', 'Pedersen', 'Anna', 'Smith', 'John', 'Irons', 'Beatrice', 'Potter'];
    
    // Rearrange into groups of two
    arr = arr.map((x, i) => i % 2 === 0 ? [x, a[i + 1]] : null).filter(x => x);
    
    // Do something we each 'mini'-array
    arr.forEach(([firstName, lastName]) => {
      console.log(firstName, lastName);
    });
    

    But in your case first- and last names would be start- and end dates?

    Login or Signup to reply.
  2. You could use the Array reduce method (doc), combined with String split (doc) to extract the data.

    Here is a simplified example that you can adapt to your specific needs. This would return "35" with the example you have provided, but works with an array of any size.

    It first compares dates for each item, reducing the array to a single string, then splits the remaining string by ‘;’ and gets the second value which is supposed to be the number.

    You obviously have to add more checks (existence of the array indexes, date format, what happens if the date is the same, etc.) but this is would be a good start.

    const data = { "Info":["A;35;Jan 20 2023;","B;45;Feb 20 2013"] }
    
    data.Info.reduce((accumulator, currentValue) => { 
        if (accumulator) {
            if (Date.parse(accumulator.split(';')[2]) > Date.parse(currentValue.split(';')[2])) {
              return accumulator
            }
        }
        return currentValue
    }, data.Info[0]).split(';')[1]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search