Compare two object arrays and remove the difference in javascript

Asked

Viewed 393 times

0

I have an array of products and variable size categories. I have to return the array of categories by deleting categories that have no linked product.

Categories:

[{
    id: 1,
    nome: Categoria 1
},
{
   id: 2,
   nome: Categoria 2
},
{
   id: 3,
   nome: Categoria 3
}]

Products:

[{
    nome: Produto 1,
    category_id: 1
},
{
    nome: Produto 2,
    category_id: 2
}]

In the above example I would like to return the array of categories by removing Category 3, since there is no product attached to it. I tried using the filter but could not remove.

let products = response.data;
let categories = categories.filter(function (element, index, array) {
    if (element.id !== self.products[index].category_id) {
        return element;
    }
});
  • And you need to do this by Javascript? It would not be convenient to do this on the server side and only deliver to the client the categories that have products?

  • Not because I need the complete categories to use elsewhere.

  • I did not understand the problem of the question to be marked as pending.

  • I believe it’s because you didn’t present your attempt, you just asked as you do. Search [Edit] and add your attempt as well as describe what was the result obtained.

1 answer

1


Small example of a filter:

const categorias = [{
    id: 1,
    nome: 'Categoria 1'
},
{
   id: 2,
   nome: 'Categoria 2'
},
{
   id: 3,
   nome: 'Categoria 3'
}];

const produtos = [{
    nome: 'Produto 1',
    category_id: 1
},
{
    nome: 'Produto 2',
    category_id: 2
}];

const categoriasFiltradas = categorias.filter(categoria => produtos.filter(produto => produto.category_id === categoria.id).length);

console.log(JSON.stringify(categoriasFiltradas));

Browser other questions tagged

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