-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}
];
5
  • 2
    Please visit help center, take tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output. Commented Apr 15, 2020 at 13:51
  • You can find your answer in the following topic Commented Apr 15, 2020 at 13:55
  • @RaduPopa, the problem is quite more simple than the referenced question, because here is only one property relevant, and not all. Commented Apr 15, 2020 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? Commented Apr 15, 2020 at 14:06
  • @AlanPaulMathew Remove all dupes, preferring undefined but leave them in if not dupes Commented Apr 15, 2020 at 14:15

2 Answers 2

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; }

Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

Same as Nina's but without a reduce.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.