skip to Main Content

I have an array of objects:

const obj = [{
  id: 1,
  name: 'A'
}, {
  id: 1,
  name: 'A'
}, {
  id: 1,
  name: 'A'
}, {
  id: 2,
  name: 'A'
}, {
  id: 2,
  name: 'A'
}]

// this method returned me one object with id=1
const filter = obj.reduce((val, index) => {
  return index === val.findIndex(v => obj.id === v.id && obj.name === o.name)
})

When I push the button I want to remove one of the duplicate object. For example I have 3 object within an array with ID=1. I want to remove only one object with ID=1 and not two. So the result must be like this:

const obj = [{
  id: 1,
  name: 'A'
}, {
  id: 1,
  name: 'A'
}, {
  id: 2,
  name: 'A'
}, {
  id: 2,
  name: 'A'
}]

2

Answers


  1. You can achieve this by finding the index of the first object with id=1 and then using Array.prototype.splice() to remove it:

    const obj = [ { id: 1, name: 'A' }, { id: 1, name: 'A' }, { id: 1, name: 'A' }, { id: 2, name: 'A' }, { id: 2, name: 'A' } ];
    
    const targetId = 1;
    const indexToRemove = obj.findIndex(item => item.id === targetId);
    
    if (indexToRemove !== -1) {
      obj.splice(indexToRemove, /*deleteCount=*/1);
    }
    
    console.log(obj);
    Login or Signup to reply.
  2. Here is code that will take any number of objects and leave a maximum of two duplicates

    const filteredObj = arr.reduce((acc, curr) => {
      acc.count[curr.id] ??= 0; // conditional assignment
      acc.count[curr.id]++;
      // If the count is less than or equal to 2, add the object to the result array
      if (acc.count[curr.id] <= 2) {
        acc.result.push(curr);
      }
      return acc;
    }, {
      count: {},
      result: []
    }).result;
    
    console.log(filteredObj);
    <script>
    const arr = [
      { id: 1, name: 'A' },
      { id: 1, name: 'A' },
      { id: 2, name: 'B' },
      { id: 2, name: 'B' },
      { id: 3, name: 'C' },
      { id: 1, name: 'A' },
      { id: 2, name: 'B' }
    ];
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search