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

213
Views
How to swap two elements of an array with empties in JavaScript?

I have an array and I want to swap two elements in the array. If the array is non-empty, I can simply do:

const swap = (arr, a, b) => {
    const temp = arr[a]
    arr[a] = arr[b]
    arr[b] = temp
}

and the function can correctly swap the value of the index a and b in the array arr.

However, if the array has some empty elements, such as [1, , , ,], and the result of the swap will be [undefined, empty, 1, empty], while the expected result should be [empty × 2, 1, empty]. So how do I modify the swap function so that the result will be correct. Or is there any way to make a specific index to be empty in an array?

Also failed:

const swap = (arr, a, b) => {
    const temp = arr[a]
    arr.splice(a, 1, arr[b])
    arr.splice(b, 1, temp)
}

Original Problem:

I have an array let arr = [1, , , ,] (which will show [1, empty × 3] in console) with length 4, and I want to move the first element to the third, that is: [empty × 2, 1, empty]. How do I achieve that?

I have tried splice and directly assign value to the array but they won't work.

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

0

You do need splice - combined with shift to get the first item

let arr = [1, , , ,]

console.log(arr)

arr.splice(2, 0, arr.shift());
console.log(arr)

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!