I have an array of objects in JavaScript and would like to filter it, if there is two events that are equel so their days concat and if there is duplicate value in days array remove it.
here is my array:
[ { event: 'approvalDate', days: [ 1, 2, 3, 4, 5] },
{ event: 'appointDate', days: [ 1 ] },
{ event: 'approvalDate', days: [ 120, 14, 9, 4, 1, 2 ] } ]
I want the result like this
[ { event: 'approvalDate', days: [ 1, 2, 3, 4, 5,120, 14, 9] },
{ event: 'appointDate', days: [ 1 ] },
]
CodePudding user response:
const items = [
{ event: 'approvalDate', days: [1, 2, 3, 4, 5] },
{ event: 'appointDate', days: [1] },
{ event: 'approvalDate', days: [120, 14, 9, 4, 1, 2] },
];
const result = [];
items.forEach((item) => {
if (!result.find((e) => e.event === item.event)) {
result.push(item);
} else {
const index = result.findIndex((e) => e.event === item.event);
result[index].days = [...new Set([...result[index].days, ...item.days])];
}
});
CodePudding user response:
You could just concat everything then deduplicate. You need to sort the array.
function go(){
let out=deduplicate([1,2,2,2,2,3,4,4,4,4,4,5,5,5,6,7,8,9,10]);
console.log(out);
}
function deduplicate(array){
array=array.sort(function(a,b){return a-b;});
let output=[array[0]];
for (let i=1;i<array.length;i ){
if(array[i] != output[output.length-1])output.push(array[i]);
}
return output;
}
