How can I compare one item in array to it's next or previous item using index numbers Take the code below as example
const arr = [
{
name: "A",
marks: 20,
},
{
name: "B",
marks: 25,
},
{
name: "C",
marks: 30,
},
];
So how can I compare B with A or C in an if statement using index numbers to get something done?
If you are using forEach then you can do as:
NOTE: Handle the first case where
i === 0according to your need
const arr = [
{
name: "A",
marks: 20,
},
{
name: "B",
marks: 25,
},
{
name: "C",
marks: 30,
},
];
const result = [];
arr.forEach((obj, index, sourceArr) => {
if (index === 0) result.push(undefined);
else {
obj.marks > sourceArr[index - 1].marks
? result.push("green")
: result.push("red");
}
});
console.log(result);