Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
How to compare items in array using index numbers?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you are using forEach then you can do as:

NOTE: Handle the first case where i === 0 according 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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!