1

Trying to filter the results in array2 based on the value type of array1 but the resultant array always prints the last value in the forEach loop.

Snippet

const array1 = [{
    name: "Audi",
    type: "sedan"
  },
  {
    name: "BMW",
    type: "sedan"
  },
  {
    name: "Benz",
    type: "suv"
  }
];
const array2 = [{
  year: "2020"
}, {
  year: "2021"
}];

let a = [];
let customObject1 = {};
let array3 = [];
array1.forEach((val1) => {
  array2.forEach((val2) => {
    if (val1.type === "sedan") {
      customObject1["label"] = "Sedan Car";
      customObject1["year"] = val2.year;
      array3.push(customObject1);
      console.log(array3);
    }
  });
});

Here's the result that I'm expecting. Could anyone please help?

array3 = [{label: 'Sedan Car', year: '2020'}, {label: 'Sedan Car', year: '2021'}]
coderpc
  • 4,119
  • 6
  • 51
  • 93
  • 1
    I absolutely cannot see how the two datasets relate to each other - You're trying to get a weird result based on what logic exactly? *"Trying to filter the results in array2"* filter what? – Roko C. Buljan Nov 21 '20 at 01:50
  • Would C# duplicate work? The same "not creating object on each iteration"... Surprising that there is no such easily searchable one in JavaScript. My mistake - to add to array in JavaScript you push it out :) – Alexei Levenkov Nov 21 '20 at 01:51
  • Does this answer your question? [Array.push() makes all elements the same when pushing an object](https://stackoverflow.com/questions/10932584/array-push-makes-all-elements-the-same-when-pushing-an-object) – Alexei Levenkov Nov 21 '20 at 01:52

4 Answers4

1

You need to clone the customObject1 each loop when you push to array3, you can use JSON.stringify() and then JSON.parse() to get a copy of that object (with a new reference in memory), otherwise you are overwriting the reference of the same object each loop. Check this to understand how JS handle objects in memory: https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0.

let a = [];
let customObject1 = {};
let array3 = [];
array1.forEach((val1) => {
  array2.forEach((val2) => {
    if (val1.type === "sedan") {
      customObject1["label"] = "Sedan Car";
      customObject1["year"] = val2.year;
      array3.push(JSON.parse(JSON.stringify(customObject1)));
      console.log(array3);
    }
  });
});
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
0

Idk what you're trying to do here. but here's how you can do it.

const array1 = [
  {
    name: 'Audi',
    type: 'sedan',
  },
  {
    name: 'BMW',
    type: 'sedan',
  },
  {
    name: 'Benz',
    type: 'suv',
  },
];
const array2 = [
  {
    year: '2020',
  },
  {
    year: '2021',
  },
];

const array3 = [];

array2.forEach((item, index) => {
  array1.forEach((item2) => {
    if (item2.type === 'sedan') {
      item.label = 'Sedan Car';
    }
  });
  array3.push(item);
});

console.log(array3);
onlit
  • 728
  • 5
  • 19
0

You are getting only the last value because you are re-using the same customObject1 instance for every array3 element. You would get better results by defining a new customObject1 instance for each element:

const array1 = [{
    name: "Audi",
    type: "sedan"
  },
  {
    name: "BMW",
    type: "sedan"
  },
  {
    name: "Benz",
    type: "suv"
  }
];
const array2 = [{
  year: "2020"
}, {
  year: "2021"
}];

let a = [];
let array3 = [];
array1.forEach((val1) => {
  array2.forEach((val2) => {
    if (val1.type === "sedan") {
      let customObject1 = {};
      customObject1["label"] = "Sedan Car";
      customObject1["year"] = val2.year;
      array3.push(customObject1);
      console.log(array3);
    }
  });
});

NOTE: This still does not produce the final results you seem to expect. That is because array1 has two sedans.

cybersam
  • 63,203
  • 6
  • 53
  • 76
0

The problem is, that the same customObject reference is used during every iteration of the inner forEach loop. I would prefer a solution without using a variable at all by passing an object directly as a parameter in the push function.

let a = [];
let array3 = [];
array1.forEach((val1) => {
  array2.forEach((val2) => {
    if (val1.type === "sedan") {
      array3.push({ label: "Sedan Car", year: val2.year });
    }
  });
});

If you want to keep your variable were it is you could also make use of object destructuring to create a copy

let a = [];
let customObject1 = {};
let array3 = [];
array1.forEach((val1) => {
  array2.forEach((val2) => {
    if (val1.type === "sedan") {
      customObject1["label"] = "Sedan Car";
      customObject1["year"] = val2.year;
      array3.push({...customObject1}) //destructuring the object;
      console.log(array3);
    }
  });
});
Martin Godzina
  • 1,470
  • 11
  • 17