How do I compare the same value in multiple arrays?

Viewed 103

I am working on a project that involves a nested array, and I need to sort 1 value from each array by size. (All arrays are in the same format e.g. [a,b,c,d]). To make it clearer, how would I choose the bigger number out of an array like time[60][x] where x is the number of arrays (it is a very strange nest).

const time = {
  15: [
    { language: 'english', raw: 105.6, acc: 93.94, wpm: 96, punctuation: false }
  ],
  30: [
    { language: 'english', raw: 66.4, wpm: 66.4, punctuation: false, difficulty: 'normal' }
  ],
  60: [
    { acc: 98.97, language: 'english', puncutation: false, wpm: 96, difficulty: 'normal' },
    { acc: 92.63, puncutation: false, language: 'english_10k', wpm: 59.19, raw: 60.99 }
  ]
};

As you can see, each array has a different number of arrays nested into it for example time[60][2] has 2 arrays in it. This is the structure of the object. I need to find the greatest value out of the wpm column for each array. Any and all help is greatly appreciated, Thank you

2 Answers

If I'm understanding your question correctly, this might be what you need:

const time = {
  15: [{wpm: 10}, {wpm: 15}, {wpm: 20}],
  30: [{wpm: 5}, {wpm: 10}, {wpm: 30},],
  60: [{wpm: 4}, {wpm: 12}, {wpm: 8},]
};

const results = {};

// iterate over the time object
for (let key in time) {
  results[key] = time[key].reduce((acc, item) => {
    if (item.wpm > acc) {
      return item.wpm;
    }
    
    return acc;
  }, 0);
}

console.log(results);

Here's a codepen: https://codepen.io/geuis/pen/VwaxWWY

Object
  .fromEntries(Object
    .entries(time)
    .map(([key, array]) => ([key, Math.max(...array.map(({ wpm }) => wpm))])));

Live example:

const time = {
  15: [
    { language: 'english', raw: 105.6, acc: 93.94, wpm: 96, puncutation: false }
  ],
  30: [
    { language: 'english', raw: 66.4, wpm: 66.4, punctuation: false, difficulty: 'normal' }
  ],
  60: [
    { acc: 98.97, language: 'english', puncutation: false, wpm: 96, difficulty: 'normal' },
    { acc: 92.63, puncutation: false, language: 'english_10k', wpm: 59.19, raw: 60.99 }
  ]
};

const maxes = Object
  .fromEntries(Object
    .entries(time)
    .map(([key, array]) => ([key, Math.max(...array.map(({ wpm }) => wpm))])));

console.log(maxes);

To preserve the entire object so that you can then access its other properties besides wpm:

Object.fromEntries(Object.entries(time).map(([key, arr]) => ([key, arr.find(({ wpm }) => wpm == Math.max(...arr.map(({ wpm }) => wpm)))])));
Related