UXCODA
UXCODA

Reputation: 1236

Unable to use variable in JS forEach

I am trying to check wether a property already exists in the otherFeatures array. I am checking this with the match variable. When I console log the results out inside match it works correctly but when I try use it in the if statement it always returns undefined

const otherFeatures = [
  {heading: "Taps", value: "Silver"},
  {heading: "Taps", value: "Bronze"},
  {heading: "Sink", value: "Ceramic"},
];

let features = [];

const featuresCheck = otherFeatures.forEach((item, index) => {
  const match = features.forEach((feat) => {
    return feat.heading === item.heading;
  });
  console.log("match", match);
  if (match) {
    console.log('match true'); 
  } else {
    features[index] = item;
  }
});

Upvotes: 0

Views: 141

Answers (1)

Barmar
Barmar

Reputation: 782315

forEach() doesn't return the result of the callback function. If you want that, you need to use map(). Since forEach() doesn't return a useful value, there's no point in assigning it to a variable.

const otherFeatures = [
  {heading: "Taps", value: "Silver"},
  {heading: "Taps", value: "Bronze"},
  {heading: "Sink", value: "Ceramic"},
];

let features = [];

otherFeatures.forEach((item, index) => {
  const match = features.map((feat) => {
    return feat.heading === item.heading;
  });
  console.log("match", match);
  if (match) {
    console.log('match true'); 
  } else {
    features[index] = item;
  }
});
console.log("features", features);

However, all arrays are considered truthy in JavaScript, even if they're empty, so if (match) will always succeed. If you want to know if any of the elements match, you should use some().

const otherFeatures = [
  {heading: "Taps", value: "Silver"},
  {heading: "Taps", value: "Bronze"},
  {heading: "Sink", value: "Ceramic"},
];

let features = [];

otherFeatures.forEach((item, index) => {
  const match = features.some((feat) => {
    return feat.heading === item.heading;
  });
  console.log("match", match);
  if (match) {
    console.log('match true'); 
  } else {
    features[index] = item;
  }
});
console.log("features", features);

Upvotes: 1

Related Questions