Array sum returns only one value

Asked

Viewed 47 times

1

Some time ago I had to execute a sum of arrays with javascript, Example:

allData[0].likes = [5,10,15,20,25];
allData[1].likes = [10,2,3,17,15];

Using a solution I found on the Internet I used the following code modified by myself:

var result = allData.reduce(function(array1, array2) {
        return array2["likes"].map(function(value, index) {
          return parseInt(value) + (parseInt(array1[index]) || 0);
        }, 0);
      }, []);

And with this it always returned a single array, in this example the value of "result" would be: [15,12,18,37,40]

It was working perfectly until this month when in the following case below it returns me only a value instead of an array.

allData[0].likes = [8,10,15,20,25];
allData[1].likes = [20];

In this case it returns only the 28 value and ignores the rest of the values

How do I change my code so it doesn’t happen?

  • in that array2[likes] the likes should be as string, right? this way array2["likes"].

  • This I had to delete a lot of data for the sake of company confidentiality but yes it is like that, already arranged in Edit.

1 answer

1


From what I understand the problem is because of the difference in the size of the array. Adjusting the size of the array can solve your problem without having to change what already exists, just by including a small snippet to make this adjustment:

let allData = [];
allData.push({ likes: [] });
allData.push({ likes: [] });

allData[0].likes = [5, 10, 15, 20, 25];
// allData[1].likes = [10,2,3,17,15];
allData[1].likes = [20];

// Analisa o array e pega o maior tamanho de array
const maxLength = Math.max(...
  allData.map(a => a.likes.length)
);

// Agora faz o ajuste para que todos os arrays tenham
// o mesmo tamanho
allData.forEach(item => item.likes = [...item.likes, ...new Array(maxLength - item.likes.length).fill(0)]);

var result = allData.reduce(function(array1, array2) {
  return array2["likes"].map(function(value, index) {
    return parseInt(value) + (parseInt(array1[index]) || 0);
  }, 0);
}, []);

console.log(result);

  • I forgot to thank you, thank you so much after I gave a little modified worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.