-1

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.

  • 5
    The code in the question is riddled with syntax errors. So the first thing is to correct those so we have an idea what the real structure is. – T.J. Crowder Sep 19 '16 at 16:13
  • @T.J.Crowder copy&paste problems I guess. But it's true that he needs to fix them! – Marcos Pérez Gude Sep 19 '16 at 16:14
  • However, this is a very simple task with SQL, if WebSQL be a reality :'( – Marcos Pérez Gude Sep 19 '16 at 16:15
  • It looks like you just want to loop over pizzas and then compare the list of ingredients to the full ingredients array. Other questions like http://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript are probably enough to get you going. – Andy Ray Sep 19 '16 at 16:16
  • Thats just example code. The issue is that i have array in array which i have to loop through (ingredients in pizzas) While i have to loop through the selected_ingredients. To make sure that i printout The right pizzas. It Will become a nested loop hell. How do I make this clean code? – lars peterson Sep 19 '16 at 16:35

2 Answers2

0

You can use a map (works in modern browsers).

var map = new Map();
for (var i=0; i < pizza.length; i++) {
  var ingString = JSON.stringify(pizza[i].ing);
  var pizzaWithIng = map.get(ingString);
  if (!pizzaWithIng) {
    pizzaWithIng = [];
    map.set(ingString, pizzaWithIng);
  }
  pizzaWithIng.push(pizza[i]);
}

var result = map.get(JSON.stringify(selected_ingredients));

The solution requires that the ingredients are sorted.

mm759
  • 1,404
  • 1
  • 9
  • 7
-1

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.

Sudharsan Selvaraj
  • 4,792
  • 3
  • 14
  • 22