Angel Sanchez Angel Sanchez - 7 months ago 22
Javascript Question

Remove object from array with Javascript/Angular

I have a function like this: pickListSelect is an array with all id to delete objects in source array, and target it is to push elements deleted from source.

function copy(pickListSelect, source, target) {

var i, id;

for (i = 0; i < pickListSelect.length; i++) {
id = pickListSelect[i];
source.splice(id,1);
}
pickListSelect = [];
}


So what I need is delete specific object from array source. I tried with that code but for example if I need to delete object with id=5, it only deleted item 5 from the list.

The structure of source array is this:

[Object, Object, Object, Object, Object, Object, Object, Object, Object]
0:Object
plantId:1
plantName:"Plant 1"

...the rest of others similar object

Answer

You need to find plant in your source by plantId first, and then delete it from original array and push to target. Open console and it should log deleted plants:

var plants = [
    {
        plantId: 1,
        plantName: 'plant 1'
    },
    {
        plantId: 2,
        plantName: 'plant 2'
    },
    {
        plantId: 3,
        plantName: 'plant 3'
    },
    {
        plantId: 4,
        plantName: 'plant 4'
    }
];

function copy(pickListSelect, source, target) {
    var i, id, el;

    for (i = 0; i < pickListSelect.length; i++) {
        id = pickListSelect[i];
        el = findPlant(source, id);
        source.splice(source.indexOf(el), 1);
        target.push(el);
    }
}

function findPlant (arr, id) {
    return arr.filter(function (plant) {
        return plant.plantId == id
    })[0]
}

var test = [];

copy([2,3], plants, test);

console.log(test);

Comments