Returning the position of a number in an array

I have an array of numbers say

let numbers = [4,7,2,0,9];

I want the numbers array to be mapped based on the size of the number in the array and return its position. I need the output to look like this

numbers = [3,4,2,1,5];

thank you

3 thoughts on “Returning the position of a number in an array”

  1. You mean this which is the simplest of the answers so far

    const arr = [4,7,2,0,9]
    
    const indicii = arr.slice(0).sort((a,b) => a-b); // copy and sort
    const res = arr.map(arrItem=> indicii.indexOf(arrItem)+1); // map indicii plus 1
    
    console.log(res)
    Reply
  2. Clone the array, and sort it ascending, and map it to pairs of [num, index + 1]. Convert the array of pairs to an object (position).

    Now map the original array, and take the position of each number from the positions object.

    const numbers = [4,7,2,0,9];
    
    const positions = Object.fromEntries(
      [...numbers]
        .sort((a, b) => a - b)
        .map((num, index) => [num, index + 1])
    );
    
    const result = numbers.map(num => positions[num]);
    
    console.log(result);

    You can use a Map instead of an object, by replacing Object.fromEntries() with the Map’s constructor:

    const numbers = [4,7,2,0,9];
    
    const positions = new Map(
      [...numbers]
        .sort((a, b) => a - b)
        .map((num, index) => [num, index + 1])
    );
    
    const result = numbers.map(num => positions.get(num));
    
    console.log(result);
    Reply
  3. let numbers = [4, 7, 2, 0, 9];
    let numbersMapped = numbers.map((x, idx) => {
      return { index: idx, value: x }
    });
    
    numbersMapped.sort((x, y) => {
      return x.value > y.value ? 1 : x.value === y.value ? 0 : -1
    });
    
    const indexes = numbersMapped.map(x => {
      return x.index
    });
    
    console.log(indexes) // [3, 2, 0, 1, 4]
    Reply

Leave a Comment