Reputation: 241
Having Data in array of arrays with duplicate arrays of Oth position. explanation Compare arrays with its zero th position and make the result accurately.
let array = [["2018-03-09", 10, 11, 0],["2018-03-10", 100, 101, 105],["2018-03-15", 20, 0, 25],["2018-03-09", 0, 0, 15],["2018-03-15", 0, 10, 0]]
let output = [];
for (let i = 0; i < array.length; i++) {
let key = array[i][0]
let index = output.findIndex(x => x[0] == key)
if (index >= 0) {
for (let k = 1; k < array[i].length; k++) {
if (array[i][k] >= output[index][i]) {
output[index][k] = array[i][k]
} else {
output[index][k] = output[index][i]
}
}
} else {
output.push(array[i])
}
}
console.log(output)
Required Output
output=[["2018-03-09",10,11,15],["2018-03-10",100,101,105],["2018-03-15",20,10,25]]
How can I achieve this?
Upvotes: 0
Views: 647
Reputation: 138437
You could use a lookup object to find previous entries with the same values, then merge them. Array destructuring is helpful to make the code clean:
const byDate = {};
const result = [];
for(const [date, ...values] of array) {
if(byDate[date]) {
values.forEach((v, i) => byDate[date][i + 1] = Math.max(byDate[date][i + 1], v));
} else {
result.push(byDate[date] = [date, ...values]);
}
}
Upvotes: 2
Reputation: 22247
Use array.reduce to build an object with the identifier (the date) as the keys, which sums the other three values. Then, use Object.values to return your desired array output.
let array = [["2018-03-09", 10, 11, 0],["2018-03-10", 100, 101, 105],["2018-03-15", 20, 0, 25],["2018-03-09", 0, 0, 15],["2018-03-15", 0, 10, 0]];
let output = Object.values(array.reduce((r, e) => {
var k = e[0];
if (!r[k]) r[k] = [k, 0, 0, 0];
r[k][1] += e[1];
r[k][2] += e[2];
r[k][3] += e[3];
return r;
}, {}));
console.log(output);
Upvotes: 0
Reputation: 6394
For better readability, you can update the array in a separate function (I kept the for
loop method you used, although we could use here a forEach()
call).
Here, updateEntry will look in an output array (entries
argument) for an existing entry
, updating it if found otherwise it will append it to the output array.
Below a working snippet.
function updateEntry(entries, entry) {
for (let i = 0; i < entries.length; i++) {
if (entry[0] != entries[i][0]) continue;
for (let j = 1; j < entry.length; j++) {
if (entry[j] >= entries[i][j])
entries[i][j] = entry[j];
}
return;
}
entries.push(entry);
}
let array = [
["2018-03-09", 10, 11, 0],
["2018-03-10", 100, 101, 105],
["2018-03-15", 20, 0, 25],
["2018-03-09", 0, 0, 15],
["2018-03-15", 0, 10, 0]
];
let output = [];
for (let i = 0; i < array.length; i++) {
updateEntry(output, array[i]);
}
console.log(output);
Upvotes: 0