Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array of array numbers

I have an array like this one:

let array = [14, 42, 1, 3]

And I would like to get the arrays number mapped to this:

[1, 0, 3, 2]

Here is the reason:

  • 1: because 14 is the second biggest number
  • 0: because 42 is the biggest number
  • 3: ...

What I have tried so far:

let sort = (array) => {
  let result = []
  let x = array.slice(0).sort((a, b) => b - a)
  for (let elem of x) {
    result.push(array.indexOf(elem))
  }
  console.log(result)
}

// Working
sort([14, 42, 1, 3]) // [1, 0, 3, 2]

// Not working, includes the index "0" two times
sort([14, 42, 14, 3]) // [1, 0, 0, 3]
// Expected: [1, 0, 2, 3]
like image 512
Jonas Avatar asked Jul 09 '19 18:07

Jonas


People also ask

How do you find array of arrays?

To initialize an array of arrays, you can use new keyword with the size specified for the number of arrays inside the outer array. int[][] numbers = new int[3][]; specifies that numbers is an array of arrays that store integers. Also, numbers array is of size 3, meaning numbers array has three arrays inside it.

How do you find an array of numbers?

//Number of elements present in an array can be calculated as follows. int length = sizeof(arr)/sizeof(arr[0]); printf("Number of elements present in given array: %d", length);

How do you access an array inside an array?

To access an element of the multidimensional array, you first use square brackets to access an element of the outer array that returns an inner array; and then use another square bracket to access the element of the inner array.

Can you have an array of arrays?

A jagged array is an array whose elements are arrays, possibly of different sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.


1 Answers

You could take the indices and sort them by taking the value from the given array.

const sort = array => [...array.keys()].sort((a, b) => array[b] - array[a]);

console.log(sort([14, 42, 1, 3]));
console.log(sort([14, 42, 14, 3]));
like image 105
Nina Scholz Avatar answered Oct 01 '22 05:10

Nina Scholz