0

Sorry for my bad English. If I have an array:

const myobj = [
{
    id: 1,
    name: 'First...'
},
{
    id: 2,
    name: 'Second...
}];

How can I remove, for example, the object with id 2? To leave the array only with first object. Which functions should I use? Thanks in advance.


Found solution:

function removeByKey(array, params){
    array.some(function(item, index) {
        if(array[index][params.key] === params.value){
            array.splice(index, 1);
            return true;
        }
        return false;
    });

    return array;
}

Then

removeByKey(myobj, {
    key: 'id',
    value: 2
})

http://jsforallof.us/2015/07/08/remove-object-by-key-from-array/

Dewagg
  • 103
  • 1
  • 8

3 Answers3

0

Use Array.prototype.filter which produces new array based on the provided condition.

const myobj = [{ id: 1, name: 'First...' }, { id: 2, name: 'Second...' }];

console.log(myobj.filter(v => v.id !== 2));

Similarly you can use Array.prototype.reduce

const myobj = [{ id: 1, name: 'First...' }, { id: 2, name: 'Second...' }];

console.log(myobj.reduce((acc, v) => v.id !== 2 ? acc.concat(v) : acc, []));
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54
  • 1
    Reduce is so overly complicated for a filter or a splice problem (depending on whether or not he wants to mutate the original) – Icepickle Jun 10 '18 at 19:12
  • @Icepickle It is a little bit more complicated and I have included it only as an option, but it is the most fundamental out of the functional methods so it is good to be aware of that option. – Matus Dubrava Jun 10 '18 at 19:14
  • but it doesn't match the problem, for the problemof filtering there is little use of reduce, not even thinking about concat on every iteration, it is pointless for the problem at hand – Icepickle Jun 10 '18 at 20:19
  • @Icepickle Please, let me repeat myself. `I have included it only as an option` and I think that `it is good to be aware of that option`. Arguing over it seems rather pointless to me. – Matus Dubrava Jun 10 '18 at 20:24
0

first, you have an array, not an object in myobj, one way of many you could do this is to remove the item by filtering:

const myFilteredArray = myobj.filter(i => i.id !== 2);

See the javascript filter function

Ivan
  • 34,531
  • 8
  • 55
  • 100
BlackICE
  • 8,816
  • 3
  • 53
  • 91
  • Thanks for your reply. I'm using Vue & socket.io. I have table with recent games (array) and I would like to remove game which ended from this array, my socket returns only ended game id. So I need to find in array key with this id and remove it from array. – Dewagg Jun 10 '18 at 19:07
0

Using filter and assuming myobj is not constant you can do the following:

myobj = [
{
    id: 1,
    name: 'First...'
},
{
    id: 2,
    name: 'Second...'
},
{
    id: 3,
    name: 'Third...'
}
];

myobj = myobj.filter(v => v.id !== 2);
console.log(myobj);
Prins
  • 1,051
  • 1
  • 6
  • 9