-1

I want to delete rows from an object array that have the same id, but other keys are different. For example, I have the following Array:

testArray = [
 {id: 1, type: 1}
 {id: 2, type: undefined}
 {id: 3, type: 0}
 {id: 3, type: undefined}
 {id: 4, type: 0}
];

testArray[2] and testArray[3] have the same id value, but I want to delete the one that has the type undefined. Final array should look like:

testArray = [
 {id: 1, type: 1}
 {id: 2, type: undefined}
 {id: 3, type: 0}
 {id: 4, type: 0}
];
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
szilard1996
  • 47
  • 2
  • 6
  • 2
    Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output. – mplungjan Apr 15 '20 at 13:51
  • You can find your answer in the following [topic](https://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript) – Radu Popa Apr 15 '20 at 13:55
  • @RaduPopa, the problem is quite more simple than the referenced question, because here is only one property relevant, and not all. – Nina Scholz Apr 15 '20 at 14:02
  • the type of the second object is undefined too. Do you want to remove duplicate objects? If so which one should remove? – Alan Paul Mathew Apr 15 '20 at 14:06
  • @AlanPaulMathew Remove all dupes, preferring undefined but leave them in if not dupes – mplungjan Apr 15 '20 at 14:15

2 Answers2

2

You could seach for same id in the result set and replace if the former type is undefined.

var array = [{ id: 1, type: 1 }, { id: 2, type: undefined }, { id: 3, type: undefined }, { id: 3, type: 0 }, { id: 4, type: 0 }],
    result = array.reduce((r, o) => {
        var index = r.findIndex(q => q.id === o.id)
        if (index === -1) r.push(o);
        else if (r[index].type === undefined) r[index] = o;
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Try this

const testArray = [
 {id: 1, type: 1},
 {id: 2, type: undefined}, 
 {id: 3, type: undefined},
 {id: 3, type: 0},
 {id: 4, type: 0}
];

let newArray = [];
testArray.forEach(item => {
  const newArrayIndex = newArray.findIndex(newItemArray => newItemArray.id === item.id);
  if (newArrayIndex < 0) return newArray.push(item);
  if (item.type === undefined) return
  newArray[newArrayIndex].type = item.type;
});

console.log(newArray)
mplungjan
  • 169,008
  • 28
  • 173
  • 236