skip to Main Content

What is the name or official term of what I want to understand below in JavaScript??

I have never been able to find a clear article explanation of what arrays do behind the scenes when swapping numbers (I think this is a short way of replacing values, if im not wrong).

const swapNumbers = (numbers: number[]) => {
  const swap = numbers.map((x: number, index: number) =>
    index % 2 !== 0 ? numbers[index - 1] : index === numbers.length - 1 && numbers.length % 2 !== 0 ? numbers[index] : numbers[index + 1]);

  console.log(swap);
};

swapNumbers([1, 2, 3, 4]);
swapNumbers([1, 2, 5, 6, 8]);

I want to understand what this is exactly doing (I want to understand the long way)… is this numbers[index + 1] (short way, which is placing the next number in line) the same as this (long way) numbers[index + 1] = numbers[index] or numbers[index + 1] = x?

What is the condition to be able to do this? (is it only in maps and other es6 functions? or can I use this in a regular for loop e.g. numbers[index - 1];?)

2

Answers


  1. Here it is written in long form.

    const swapNumbers = (numbers) => {
      const swap = numbers.map((x, index) => 
      index % 2 !== 0 ? numbers[index - 1] : index === numbers.length - 1 && numbers.length % 2 !== 0 ? numbers[index] : numbers[index + 1]);
    
      console.log(swap);
    };
    
    const swapNumbers2 = (numbers) => {
        let swap= [];
        for (let index = 0; index < numbers.length; index++) {
            if (index % 2 !== 0) {
                swap.push(numbers[index - 1]);
            }
            else if (index === numbers.length - 1 && numbers.length % 2 !== 0) {
                swap.push(numbers[index]);
            }
            else {
                swap.push(numbers[index + 1]);
            }
        }
        console.log(swap);
    }
    
    swapNumbers([1,2,3,4]);
    swapNumbers2([1,2,3,4]);
    swapNumbers([1, 2, 5, 6, 8]);
    swapNumbers2([1, 2, 5, 6, 8]);
    Login or Signup to reply.
  2. Here is a simpler alternative in Vanilla JavaScript (swapping in-place):

    const swap=nums=>
      (nums.forEach((x,i,a)=>{
        if(i%2) [a[i-1],a[i]]=[x,a[i-1]]
      }),nums);
    
    [[1,2,3,4],[1,2,5,6,8]].map(a=>
      console.log(swap(a)));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search