-1

I have an array of objects like this:

[ 
  {id: 0, title: 'A'},  
  {id: 2, title: 'C'},  
  {id: 1, title: 'B'}, 
  {id: 0, title: 'A'},  
]

Object to remove from array:

{id: 0, title: 'A'}

How can I delete the first instance of the object from an array of objects to produce the following output:

[ 
  {id: 2, title: 'C'},  
  {id: 1, title: 'B'}, 
  {id: 0, title: 'A'},  
]

Maybe using filter or map?

FoundingBox
  • 580
  • 2
  • 7
k bro
  • 59
  • 10

4 Answers4

4

If you only want to remove the first instance of the object you can do the following with findIndex() and splice()

const obj = { id: 0, title: "A" };
const index = arr.findIndex((i) => i.id === obj.id && i.title === obj.title);
arr.splice(index, 1);

It would be quickest to check for the matching object by using the object properties like I used above. If you have a large object with lots of properties and it might be easier to use something like lodash's isEqual utility. arr.findIndex(i => isEqual(i, obj))

FoundingBox
  • 580
  • 2
  • 7
  • your solution seem to be the correct solution based on the description - eventhough OP's example makes no sense – Tibebes. M Jan 16 '21 at 07:27
  • 2
    In case you want to keep the original array `arr` then simply precede the above action with a shallow copy assignment like `b=[...arr];b.splice(b.findIndex(o=>o.title=="A"&&o.id==0),1)`. – Carsten Massmann Jan 16 '21 at 07:38
  • Thanks. It's is solution for my problem. P.S Sorry guys if my question makes some problems for all of you. – k bro Jan 16 '21 at 07:42
3

Try to do this by id.

const collection = [{ id: 0, title: 'A' }, { id: 2, title: 'C' }, { id: 1, title: 'B' }, { id: 0, title: 'A' }, { id: 2, title: 'C' }, { id: 0, title: 'C' }];

const updatedCollection = collection.filter(({ id }) => id !== 0);

console.log(updatedCollection);
0
 var arr = [1,2,3,5,7,5,9,11,13,5,9,0];
    
    for( var i = 0; i < arr.length; i++){ 
                                   
        if ( arr[i] === 5) 
        { 
            arr.splice(i, 1); 
            i--; 
        }
    }
ppwater
  • 2,315
  • 4
  • 15
  • 29
  • 3
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – ppwater Jan 16 '21 at 07:24
0

const arr=[ {id: 0, title: 'A'},  {id: 2, title: 'C'},  {id: 1, title: 'B'}, {id: 0, title: 'A'},  {id: 2, title: 'C'} ]
const arrupdate = arr.filter(({ id }) => id !== 1);
console.log(arrupdate);
Divyanshi Mishra
  • 110
  • 1
  • 11