I AM LOOKING TO COMBINE DUPLICATED ITEMS AND THEN DELETE THEM
here is the sample array for testing:
var arr = [{
'id': 1,
'text': 'ab'
}, {
'id': 1,
'text': 'cd'
}, {
'id': 2,
'text': 'other'
}, {
'id': 3,
'text': 'afafas'
}, {
'id': 1,
'text': 'test'
}, {
'id': 4,
'text': 'asfasfa'
}];
the expected result should be:
[{
'id': 1,
'text': "[ab] [cd] [test]"
}, {
'id': 2,
'text': 'other'
}, {
'id': 3,
'text': 'afafas'
}, {
'id': 4,
'text': 'asfasfa'
}]
the flow of operation goes like this > if there are items with duplicate IDs, the text field of those items should be merged into one and duplicates must be removed to keep unique values based on the text field. For example, text: "[text1] [text2] [text3] [text4]" You can refer to my previous question Merge duplicated items in array but the existing answers only handle scenarios with 2 duplicates.
I have tried the following code, however it only handles cases with 2 duplicates and fails when there are 3 or more duplicates:
arr.forEach(function(item, idx){
//Now lets go through it from the next element
for (var i = idx + 1; i < arr.length; i++) {
//Check if the id matches
if (item.id === arr[i].id) {
//If the text field is already an array just add the element
if (arr[idx].text.constructor === Array) {
arr[idx].text.push('[' + arr[i].text + ']');
}
else { //Create an array if not
arr[idx].text = new Array('[' + arr[idx].text + ']', '[' + arr[i].text + ']');
}
//Delete this duplicate item
arr.splice(i, 1);
}
}
});