How to compare adjacent elements in 2D array if duplicate?

Viewed 370

I have a 2D array:

var arr1 = [["Egypt","Grid",50],["Egypt","Grid",10],["Nigeria","Grid",20],["Ghana","Grid",60],["Egypt","Grid",30]]

I want to check the first element of each array, e.g. Egypt, Nigeria and Ghana to see if they are duplicates. But I only want it to check against the next element not against all elements in the array. If one or more elements are duplicated next to each other, I want to return one array summing the elements at position 2 (50,10,20,60,30)

This should result in :

var arr2 = [["Egypt","Grid",60],["Nigeria","Grid",20],["Ghana","Grid",60]],["Egypt","Grid",30]]

Note how even though there are 3 arrays with "Egypt", it only combines where they are next to each other.

I have tried both map and for loop but don't have anything that is close to working. This is what I've started with:

arr1.map(function (unit, index, array) {
var length = array.length
if (index < length - 2) {
  var next = array[index + 1][0]
  if (unit[0] === next) {
    }
  }
})

This works to check if elements are duplicates. I think I need to next put the duplicates into a separate array which I can then reduce but am not sure how to do that. Any help in pointing me in the right direction would be great. Thanks!

4 Answers

You can use a simple for loop iterating over each array except the last and checking if the first element of the current iterated element matches the first element of current+1.

If they match, sum the third elements of each and assign to the current iterated array, delete current+1 (here using splice()) and decrement i to recheck the same index again.

var arr1 = [
  ['Egypt', 'Grid', 50],
  ['Egypt', 'Grid', 10],
  ['Nigeria', 'Grid', 20],
  ['Ghana', 'Grid', 60],
  ['Egypt', 'Grid', 30],
];

for (let i = 0; i < arr1.length - 1; i++) {
  if (arr1[i][0] === arr1[i + 1][0]) {
    arr1[i][2] = arr1[i][2] + arr1[i + 1][2];
    arr1.splice(i + 1, 1);
    i--;
  }
}

console.log(arr1);

You can create a grouping array and in which you only push the element if an only if the last elments country and category doesn't match with the last element in the grouping array or if there is no element in the grouping

You can use for..of loop

var arr1 = [
  ["Egypt", "Grid", 50],
  ["Egypt", "Grid", 10],
  ["Nigeria", "Grid", 20],
  ["Ghana", "Grid", 60],
  ["Egypt", "Grid", 30],
];

const grouping = [];

for (let [country, category, num] of arr1) {
  const last = grouping[grouping.length - 1];
  const [lastCountry, lastCategory, lastNum] = last ?? [];

  lastCountry && lastCountry === country && lastCategory === category
    ? (last[2] += num)
    : grouping.push([country, category, num]);
}

console.log(grouping);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

Here is a solution with reduce. For easing the destructuring I have chosen to first prepend results to the accumulator to then finally reverse that result with reverse:

let arr = [["Egypt","Grid",60],["Nigeria","Grid",20],["Ghana","Grid",60],["Egypt","Grid",30]];

let result = arr.slice(1).reduce(([[x, y, z], ...acc], [a, b, c]) =>
    a === x && b == y ? [[a, b, z + c], ...acc]
                      : [[a, b, c], [x, y, z], ...acc]
, [arr[0]]).reverse();

console.log(result);

var arr1 = [
            ["Egypt","Grid",50],
            ["Egypt","Grid",10],
            ["Egypt","Grid",10],
            ["Nigeria","Grid",20],
            ["Nigeria","Grid",20],
            ["Nigeria","Grid",20],
            ["Nigeria","Grid",20],
            ["Nigeria","Grid",20],
            ["Ghana","Grid",60],
            ["Egypt","Grid",30]
           ];

var i=0;
var j=1;
while (j<arr1.length){
  if (arr1[i][0] === arr1[j][0]){
    arr1[i][2] += arr1[j][2];
    arr1.splice(j,1);
    continue
  }
  i++;
  j++;
}

console.log(arr1)

Related