다음과 같은 배열의 배열이 있다고 가정합니다 -
const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];
우리는 그러한 배열을 취하는 함수를 작성해야 합니다. 모든 하위 배열에는 정확히 세 개의 요소가 있습니다.
우리의 함수는 첫 번째 요소로 반복되는 값이 있는 하위 배열을 필터링해야 합니다. 또한 하위 배열의 경우 기존의 반복되지 않는 대응 요소에 세 번째 요소를 추가해야 합니다.
따라서 위 배열의 경우 출력은 다음과 같아야 합니다. -
const output = [[12345, "product", "25"],[1234567, "other", "10"]];
예시
이에 대한 코드는 -
const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567,
"other", "10"]];
const addSimilar = (arr = []) => {
const res = [];
const map = {};
arr.forEach(el => {
const [id, name, amount] = el;
if(map.hasOwnProperty(id)){
const newAmount = +amount + +res[map[id] - 1][2];
res[map[id] - 1][2] = '' + newAmount;
}else{
map[id] = res.push(el);
}
});
return res;
}
console.log(addSimilar(arr)); 출력
콘솔의 출력은 -
[ [ 12345, 'product', '25' ], [ 1234567, 'other', '10' ] ]