Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
How to match array with onther array inside an object ? (Js)

begginer developer (JS,ReactNative) . i want to match an array of ingridients thats passed to the function as a parameter to extricate the recipies thats match . iv'e tryied diffrent functions like map and filter but without succsess . i need to use PureJs function .

Example :

             Ingridients = ['eggs', 'lemon']   ----->   (Passed as a parameter)

             Recipies = [
                          {
                            _id:1,
                            _recipieName:"Eggs and Lemon",
                            _recipieIngridients:["eggs","lemon"]
                          },
                          {
                            _id:2,
                            _recipieName:"Onther Recipie",
                            _recipieIngridients:["water","bread","blablabla"]
                           }
                         ]

                i need that result-->

                     NewArray = [
                          {
                            _id:1,
                            _recipieName:"Eggs and Lemon",
                            _recipieIngridients:["eggs","lemon"]
                          }

Thx.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

This can achieved by doing the following

Exact match:

const matchRecipe = (ingredients) => 
   Recipies
      .filter(r => r._recipieIngridients.length === ingredients.length && r._recipieIngridients.every((ingredient, index) => ingredient === ingredients[index]))

Here, I'm filtering the recipies using filter, and as a predicate, I'm using every to check that each element inside the _recipieIngridients matches each element inside ingredients by using the index that is taken as a second argument from the every function

If you don't need it to match the position of the element, you can sort both ingredients so that they should all match whatever the previous order is

A more simplified version without using nested prototype functions:

const matchRecipe = (ingredients) => Recipes.filter(recipe => {
  if (ingredients.length !== recipe._recipieIngridients) return false
  // Sort both if needed
  for (let i = 0; i < recipe._recipieIngridients.length; i++) {
    if (recipe._recipieIngridients[i] !== ingredients[i]) return false
  }
  return false
})

Hope you find this helpful

Edit (1) For your comment, if you want partial matching, you can do the following

const matchRecipe = (ingredients) => 
   Recipies
      .filter(r => r._recipieIngridients.length === ingredients.length && r._recipieIngridients.some((ingredient) => ingredients.include(ingredient)))

The prototype function some will return true once any of the elements match any of the ingredients by using the include function

about 4 years ago · Juan Pablo Isaza Relatório

0

You can put the ingredients into Set to compare them efficiently, for example

const recipies = [
  {
    _id:1,
    _recipieName:"Eggs and Lemon",
    _recipieIngridients:["eggs","lemon"]
  },
  {
    _id:2,
    _recipieName:"Onther Recipie",
    _recipieIngridients:["water","bread","blablabla"]
  },
  {
    _id:3,
    _recipieName:"Eggs with Cheese Recipie",
    _recipieIngridients:["eggs", "cheese"]
  } 
];

function filterByIngridients(recipies, ingridients, howMatch = 'every') {
  const set = new Set(ingridients);
  return recipies.filter((r) => {
    return r._recipieIngridients[howMatch]((r) => set.has(r));
  });
}

Now you can match every ingredient

let output = filterByIngridients(recipies, ['eggs', 'lemon']);
console.log(output);

Output:

[
  {
    _id: 1,
    _recipieName: 'Eggs and Lemon',
    _recipieIngridients: [ 'eggs', 'lemon' ]
  }
]

Or some ingredients

output = filterByIngridients(recipies, ['eggs', 'lemon'], 'some');
console.log(output);

Output:

[
  {
    _id: 1,
    _recipieName: 'Eggs and Lemon',
    _recipieIngridients: [ 'eggs', 'lemon' ]
  },
  {
    _id: 2,
    _recipieName: 'Eggs with Cheese Recipie',
    _recipieIngridients: [ 'eggs', 'cheese' ]
  }
]
about 4 years ago · Juan Pablo Isaza Relatório

0

You should try something like that:

const availableReciepes = Recipies.reduce((result, reciepe)=>{
    let hasAllIngredients = Ingridients.reduce((carry, ingredient)=>{
        if(!reciepe.ingredient) 
            return false;
        return carry;
    }, true);

    if(hasAllIngredients){
        result.push(reciepe);
    }

    return result;
}, []);

Basically, for every recipe, check if you have all the ingredients, then adds it to the reduce carry.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda