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 number0
: because 42
is the biggest number3
: ...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]
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.
//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);
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.
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.
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]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With