How to find an element inside an array of objects by the Id?

0

I have two arrays , where one of them contains integers ( array1 ) and another contains array2 Id , Description and Banners .

I need to find and remove all of the array2 elements that match every array1 integer.

I have tried to use the .find(x => x.Id === index) function, but I did not succeed.

I'm using JavaScript , jQuery and KnockoutJS .

    
asked by anonymous 17.11.2017 / 13:02

2 answers

1

You can use Array # splice for 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; }
    
17.11.2017 / 13:12
1

Use 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)
    
17.11.2017 / 15:07