I DON'T WANT ONLY DELETE DUPLICATED. I WANT TO MERGE DUPLICATED AND THEN DELETE
this is my test array:
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'
}];
and result must be this:
[{
'id': 1,
'text': "[ab] [cd] [test]"
}, {
'id': 2,
'text': 'other'
}, {
'id': 3,
'text': 'afafas'
}, {
'id': 4,
'text': 'asfasfa'
}]
flow is next > I have items that may have duplicated. if item's ID's is equal tu other, I mean if ID is duplicated then TEXT fild must be merged into one and duplicated must be deleted and must stay unique with text field, eg. text: "[text1] [text2] [text3] [text4]" this is my old question Merge duplicated items in array but written answers only work for 2 duplicates.
this code is what I try but it only work 2 duplicates, maybe I have 3 or more duplicates this code don't work
arr.forEach(function(item, idx){
//Now lets go throug 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);
}
}
});