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

246
Views
How to handle the case if item is undefined?

In an array of objects I am trying to create a new property based on another array of numbers.
The problem is that the number of array has one less element, therefore it gets undefined in the last index of array of objects.
How to handle that case, if the new created property is undefined? See the code example below

const sortArr = [3, 2, 1];

const items= [
  {
    a: 1,
  },
  {
    a: 2,
  },
  {
    a: 3,
  },
  {
    a: 4,
  },
];

const res =
items.map((item, idx) => ({
    ...item,
      sortItem:sortArr[idx]
  }));
  
  console.log(res)

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

0

if it's the last in the array then show nothing/empty string

To use an empty string as fallback if sortArr[inx] does not exist, use the Nullish coalescing operator (??) operator:

sortItem: sortArr[idx] ?? ''

const sortArr = [3, 2, 1];
const items= [{a: 1, }, {a: 2, }, {a: 3, }, {a: 4, }, ];

const res = items.map((item, idx) => (
    {
        ...item,
        sortItem: sortArr[idx] ?? ''
    }
));

console.log(res)

about 4 years ago · Juan Pablo Isaza Report

0

You can set sortItem based on whether idx is less than sortArr.length

sortItem: idx < sortArr.length ? sortArr[idx] : "no element at that position"

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!