DEV Community

bomoniyi
bomoniyi

Posted on

Performing action on elements in an array

const temperatures = [
  { degrees: 69, isRecordTemp: false },
  { degrees: 82, isRecordTemp: true },
  { degrees: 73, isRecordTemp: false },
  { degrees: 64, isRecordTemp: false }
];

const newTemps = temperatures.map(temperature => 
temperature.degrees > 70 ? { ...temperature, isHigh: true } : temperature 
);

newTemps.forEach(temperature => {
   if (temperature.isHigh) {
     console.log(`Temperature ${temperature.degrees} was a record high last week!`);  
   }
})
// console.log(newTemps);
Enter fullscreen mode Exit fullscreen mode

Thus adds isHigh to elements given a conditional is granted.

const temperatures = [
  { degrees: 69, isRecordTemp: false },
  { degrees: 82, isRecordTemp: true },
  { degrees: 73, isRecordTemp: false },
  { degrees: 64, isRecordTemp: false }
];

const newTemps = temperatures.map(temperature => {
   temperature.isHigh = true; 
   return temperature;
});
console.log(newTemps);
Enter fullscreen mode Exit fullscreen mode

Thus adds isHigh to all elements in the array.

Top comments (0)