lars peterson lars peterson - 2 months ago 25
Javascript Question

javascript: avoid nested in nested loops

I have trouble getting my head around this code without making some ugly nested in nested loops.

I have the following:

var selected_ingredients = [ {name:'ing4},{name:'ing13},{name:'ing14},{name:'ing21},{name:'ing23} ];

var pizza = [ {name:'pizza1',ing[ {name:'ing12},{name:'ing2} ]}, {name:'pizza2',ing[ {name:'ing4},{name:'ing13} ]}, {name:'pizza3',ing[ {name:'ing14},{name:'ing21},{name:'ing2} ]}, {name:'pizza4',ing[ {name:'ing14},{name:'ing3} ]}, {name:'pizza5',ing[ {name:'ing21},{name:'ing14},{name:'ing5} ]} ];


I want the following:

i want the code only to printout the pizzas that have the same ingredients that can be found in selected_ingredients array.

how should I do this code with without making the code slow from all the loops in loops also when the arrays can contain 1000 of pizza items.

Answer

You can use .filter() method to filter an array based on any conditions. Look at below example code.

var filtered_result = pizza.filter(function(pizza_detail){
  return pizza_detail.ing.sort(arraySort) == selected_ingredients.sort(arraySort);
})

function arraySort(a,b){
  return a.attributes.name < b.attributes.name ? 1 : -1;
}

Since your Json objects are not sorted,you need to sort it before comparing it with selected_ingrediants array.