Group javascript mutliarray by indexes and get sum and average

javascript sum of numbers
calculate average javascript
javascript sum array of objects
javascript sum array values by key
javascript average array of objects
sum of array using for loop in javascript
write a javascript program to compute the sum of an array of integers
javascript average of three numbers

I have a multiarray in Javascript with the following format

[ [string, string, string, number, number], ......]

For example

[
['John', 'Apple', 'Monday', 1, 4.5],
 ['John', 'Orange', 'Monday', 2, 3],
 ['John', 'Apple', 'Monday', 1, 2.5]
]

How can I group the above by the first three items (the strings) and get the sum of the first number and the average of the second number?

The result of above:

[
['John', 'Apple', 'Monday', 2, 3.5],
 ['John', 'Orange', 'Monday', 2, 3],
]

I used to do this with underscore, but now I need to use just Javascript or jQuery.

I found similar questions (not exactly) but didn't help a lot


You could take an object and collect the values for later generating the average.

var array = [['John', 'Apple', 'Monday', 1, 4.5], ['John', 'Orange', 'Monday', 2, 3], ['John', 'Apple', 'Monday', 1, 2.5]],
    result = Object
        .values(array.reduce((r, a) => {
            var key = a.slice(0, 3).join('|');
            if (!r[key]) {
                r[key] = a.slice().concat(1);
                return r;
            }
            r[key][3] += a[3];
            r[key][4] += a[4];
            r[key][5]++;
            return r;
        }, Object.create(null)))
        .map(a => a.slice(0, 4).concat(a[4] / a[5]));

console.log(result);

How should the javascript or jquery code look like to create Array3 and Array4? {sum:0, count:0}; } groups[item].sum += Array2[index]; // sum values create the averages array var Array4 = $.map(groups,function(value,key){ return I agree with another poster that it might be better to find another way to  Just iterate through the array, since your values are strings, they have to be converted to an integer first. And average is just the sum of values divided by the number of values. improve this answer. edited Oct 20 '14 at 15:27. 11 bronze badges. answered Apr 28 '12 at 1:54. 11 silver badges. 25 bronze badges.


One option is using .reduce() to group the array. Use .map() and .reduce() to get the total, average and construct the final array.

let arr = [
  ['John', 'Apple', 'Monday', 1, 4.5],
  ['John', 'Orange', 'Monday', 2, 3],
  ['John', 'Apple', 'Monday', 1, 2.5]
];

let result = [...arr.reduce((c, v) => {
  let k = v[0] + v[1] + v[2];
  c.set(k, c.has(k) ? [...c.get(k), v] : [v]);
  return c;
}, new Map()).values()].map(o => {
  let t = o.reduce((c, v) => [c[0] + v[3], c[1] + v[4]], [0, 0]);
  return [o[0][0], o[0][1], o[0][2], t[0], (t[1] / o.length)];
});

console.log(result);

Simple method: It uses a simple method to access the array elements by an index number and use the loop to find the sum and product of values of an Array using​  The sum in this case is 6. After calculating the sum, we then count how many numbers there are. In this case, we have 3 numbers. That means that in order to get the average number, we must divide 3 into 6, which gives us 2. 6 / 3 = 2. Now, lets take the formula above and apply it to JavaScript. Calculating the average / mean using JavaScript.


The below may do the trick for you. I've left out the adding and average calculations, but the below structure of the code will do the matching of existing data.

const comparitorIndexes = [0,1,2]
array.reduce((acc, curr) => {
    const accIndex = acc.findIndex(x => comparitorIndexes.every(i => x[i] === curr[i]))
    if (accIndex > -1) {
        // Do sum and average here and return accumaltor
    } else {
        return [ ...acc, curr ]
    }
}, [])

The JavaScript array reduce method seems to give people trouble. A common application for .reduce() is to calculate the average of an array. We're not telling JavaScript how to run a loop and keep track of indexes. We use an object to keep track of multiple values in a single return value. function  JavaScript does not provide the multidimensional array natively. However, you can create a multidimensional array by defining an array of elements, where each element is also another array. For this reason, we can say that a JavaScript multidimensional array is an array of arrays. The easiest way to define a multidimensional array is to use the


var data = [
            ['John', 'Apple', 'Monday', 1, 4.5],
            ['John', 'Orange', 'Monday', 2, 3],
            ['John', 'Apple', 'Monday', 1, 2.5]
          ];
          
function groupData(data) {
  return data.reduce(function(acc, item) {
    if (item.length === 5) {
      var found = false;
      var lit = item.slice(0,3);
      var numSum = item.slice(3,4);
      var numAvg = item.slice(4,5);      
      for (var i in acc) {
        var accLit = acc[i].slice(0,3);
        if (accLit[0] === lit[0] && accLit[1] === lit[1] && accLit[2] === lit[2]) {
          found = true;
          var accNumSum = acc[i].slice(3,4);
          var accNumAvg = acc[i].slice(4,5);
          acc[i][3] = parseFloat(numSum) + parseFloat(accNumSum);
          acc[i][4] = (parseFloat(numAvg) + parseFloat(accNumAvg)) / 2;          
        }        
      }      
      if (!found) {        
        acc.push(item);        
      }
      return acc;
    }    
  }, []);
}

//function match

var result = groupData(data);
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

But quite often we find that we need an ordered collection, where we Methods push and unshift can add multiple elements at once: To extract an element from the end, the pop method cleans the index and shortens length . The task is: find the contiguous subarray of arr with the maximal sum of items. JavaScript exercises, practice and solution: Write a JavaScript function to calculate the sum of values in an array.


Here's a nice and generic way, no matter how many duplicates you have, of doing it:

const arr = [
 ['John', 'Apple', 'Monday', 1, 4.5],
 ['John', 'Orange', 'Monday', 2, 3],
 ['John', 'Apple', 'Monday', 1, 2.5]
]

const newArr = arr.reduce((acc, curr)=> {
const key = `${curr[0]}_${curr[1]}_${curr[2]}`

if (!acc[key]) {
  acc[key] = [];
 }

acc[key].push(curr);
if(acc[key].length > 1) {
  const firstNum = acc[key].map(nestedArr=>  nestedArr[3])
  const secondNum = acc[key].map(nestedArr=> nestedArr[4])

  const sum = firstNum.reduce((a, b)=> a + b)
  const average = secondNum.reduce((a, b)=> (a + b) / 2)

  const newAcc = acc[key][0].slice(0, 3).concat(sum, average)

  acc[key] = [newAcc]
}
return acc;
}, {})

console.log(newArr) Output

{ John_Apple_Monday: ["John", "Apple", "Monday", 2, 3.5], John_Orange_Monday: ["John", "Orange", "Monday", 2, 3] }

I kept as a key_value because that might also help. But you can simply get the keys of that object with Object.values(newArr)

To make things easier, in this chapter they are split into groups. Here and in other array methods, negative indexes are allowed. element with multiple others in the process, but it tries to make as few comparisons On the first run, sum is the initial value (the last argument of reduce ) Get average age. A few people have suggested adding a .sum() method to the Array.prototype.This is generally considered bad practice so I'm not suggesting that you do it. If you still insist on doing it then this is a succinct way of writing it:


When you read about Array.reduce and how cool it is, the first and sometimes the only example you find is the sum of numbers. const users = [ { id: 11, name: '​Adam', age: 23, group: 'editor' }, { id: 47, name: 'John', age: 28, group: Then the first value of the nested will be used as the initial acc value. But, since you already have a nodeList that is an array-like list of the items from getElementsByClassName(), there is no need to get them all over again. As such, you can much more safely rewrite the code to use that and it should also protect you from trying to reference a non-existent item since getElementsByClassName() won't return null items.


Two-dimensional (2D) arrays are indexed by two Find the average rating by the reviewer in row 2. int sum = 0; double average = (double) sum / 4;. 7. 3. 9. 6​. Either flatten the objects first, like { brand: 'Audi', color_value: 'black' } or pass a function taking each object in the array, returning the desired value on that object. Eg. instead of const value = obj [key] do const value = keyFn (obj). Another approach would be to pass a key with dots, like 'color.value' and have the function parse that


This includes arrays and array-like constructs such as Array objects Remember​, JavaScript Array indexes are 0-based: they start at 0 , not 1 . Using this characteristic of JavaScript arrays, multi-dimensional arrays can be created. Get the latest and greatest from MDN delivered straight to your inbox. The reduce () method reduces the array to a single value. The reduce() method executes a provided function for each value of the array (from left-to-right). The return value of the function is stored in an accumulator (result/total). Note: reduce() does not execute the function for array elements without values.