How to find an element within an object array by Id?

Asked

Viewed 920 times

0

I have two arrays, where one of them contains integer numbers (array1) and another contains objects (array2) with properties such as Id, Description and Numerovinculo.

I need to find and remove from all elements of array2 which correspond to each integer(value) of array1.

I’ve tried using the function .find(x => x.Id === index) but I was unsuccessful.

I’m using JavaScript, jQuery and KnockoutJS.

2 answers

1


One can use the Array#splice to remove a certain index from the array.

let a1 = [2,4,6],
    a2 = [
    {id: 1, nome: "Teste 1"},
    {id: 2, nome: "Teste 2"},
    {id: 3, nome: "Teste 3"},
    {id: 4, nome: "Teste 4"},
    {id: 5, nome: "Teste 5"},
    {id: 6, nome: "Teste 6"}
    ];

// removendo os IDs pares em a1
a2.forEach( (item, index) => {
    // se o id do array de objetos estiver em a1
    if (a1.indexOf(item.id) > -1)
        a2.splice(index,1) // entao remove
});

console.log(a2)
.as-console-wrapper { max-height: 100% !important; top: 0; }

1

Use the grep:

var array1 = [1,2,3]

var array2 = [
    {id: 1},
    {id: 2},
    {id: 3},
    {id: 4},
    {id: 5},
    {id: 6}
];

var diferenca = []

jQuery.grep(array2, function(item) {
    if (jQuery.inArray(item.id, array1) == -1) diferenca.push(item);
});

console.log(diferenca)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.