1
var tempStoreFood = [];
var sameFoodID = [];
var differentFoodID = [];
var finalStoreFood = [];

console.log("Temporary stored food", tempStoreFood);
console.log("Same Food Group", sameFoodID);
console.log("Different Food Group", differentFoodID);
console.log("Concatenate");

for (i = 0; i < self.foods.length; i++) {
  var foodBrand = self.foods[i];
  var foodBrandID = self.foods[i].brand_id;
  tempStoreFood.push(foodBrand);
  for (j = 0; j < tempStoreFood.length; j++) {
    var foodID = tempStoreFood[j].brand_id;
    var singleFood = tempStoreFood[j];
    if (foodID == foodBrandID) {
      sameFoodID.push(singleFood);
      break;
    }
    if (foodID !== foodBrandID) {
      differentFoodID.push(singleFood);
      break;
    }
  }

out put of the code

from the output i have got the samefoodID array and different food id array. now i want to group it as this(final output). any idea how can i do this using javascript.

final output

Siva K V
  • 9,737
  • 2
  • 13
  • 29
RIYAL
  • 37
  • 1
  • 7
  • Your screenshots don't show any details about what is actually in your arrays. Post your input and expected output in your question, not as images. – Cully Jun 13 '20 at 06:12
  • 1
    Does this answer your question? [How to merge two arrays in JavaScript and de-duplicate items](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – Raul Sauco Jun 13 '20 at 06:23

4 Answers4

0

If you are expecting the final output as an array like,

arrayMergedFood = array(arraySameFood, arrayDifferentFood)

then create a new array arrayMergedFood, then push the array arraySameFood and arrayDifferentFood on to that array. Avoid mutation.

0

You can use spread operator to merge array.

var arr1 = [1,2,3,4]
var arr2 = [ ...arr1, 5,6,7,8]
console.log(arr2)
Santosh
  • 2,743
  • 4
  • 26
  • 57
0

You can use .concat() method

var array1 = [1, 2, 3];
var array2 = ['a', 'b', 'c'];
var array3 = array1.concat(array2);

console.log(array3);
Alyona Yavorska
  • 567
  • 2
  • 13
  • 20
0

var sameFoodID = [1,2,3];
var differentFoodID = [4,5];
var mergeResult = [...sameFoodID,...differentFoodID];

console.log(mergeResult);

The spread operator is a useful and quick syntax for adding items to arrays, combining arrays or objects.

karthicvel
  • 305
  • 2
  • 5