Mohammad Gheydari - 2 years ago 95
Javascript Question

JavaScript array flatten with an if statment

flatten two array with an if statment
I have array1 and array2
I want array3

``````<script>
var array1 = [[5,10],[6,10],[7,10],[8,10],[9,10]];
var array2 = [[1,10],[2,10],[3,10],[4,10],[5,40],[6,40]];

// only the second number will add if they are different
// [5,10] + [5,40]
// [6,10] + [6,40]

// array3 = [[1,10],[2,10],[3,10],[4,10],[5,50],[6,50],[7,10],[8,10],[9,10]];

</script>
``````

This is a proposal with `Array#forEach()` in a single loop and a temporary object.

``````var array1 = [[5, 10], [6, 10], [7, 10], [8, 10], [9, 10]],
array2 = [[1, 10], [2, 10], [3, 10], [4, 10], [5, 40], [6, 40]],
array3 = [];

array2.concat(array1).forEach(function (a) {
if (!this[a[0]]) {
this[a[0]] = [a[0], a[1]];
array3.push(this[a[0]]);
return;
}
if (this[a[0]][1] !== a[1]) {
this[a[0]][1] += a[1];
}
}, Object.create(null));

document.write('<pre>' + JSON.stringify(array3, 0, 4) + '</pre>');``````

Solution with `for` loop

``````var array1 = [[5, 10], [6, 10], [7, 10], [8, 10], [9, 10]],
array2 = [[1, 10], [2, 10], [3, 10], [4, 10], [5, 40], [6, 40]],
array3 = [],
i,
temp = Object.create(null),
array = array2.concat(array1);

for (i = 0; i < array.length; i++) {
if (!temp[array[i][0]]) {
temp[array[i][0]] = [array[i][0], array[i][1]];
array3.push(temp[array[i][0]]);
continue;
}
if (temp[array[i][0]][1] !== array[i][1]) {
temp[array[i][0]][1] += array[i][1];
}
}

document.write('<pre>' + JSON.stringify(array3, 0, 4) + '</pre>');``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download