-2

if i have this nested array

let arr=[['g',10000],['s',500],['b',3],['a',200]]

I want to compare the nums in each arr so that the letter with the highest num is biggest so for example here 'g'should be greater than 's'.

i tried loops and iterations i made 2 loops to check each number in each array and compare it but theyre just not working like when i put

console.log(arr[0][0]>arr[1][0])

the output is false but i want it to be true because the array that has g has the number=10000 which is bigger than the number that the letter 's' is with in the same array. so i need help with this

pilchard
  • 12,414
  • 5
  • 11
  • 23
  • 2
    [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) with a custom compare function – knittl Aug 13 '23 at 08:31
  • 1
    Just because a value is next to another value in an array won't magically change its value. If you want to compare by number then use the relevant index `console.log(arr[0][1]>arr[1][1])` – pilchard Aug 13 '23 at 08:34
  • see: [Override default behavior of comparison operators in JavaScript](https://stackoverflow.com/questions/5627751/override-default-behavior-of-comparison-operators-in-javascript) or [How to perform less than/greater than comparisons on custom objects in javascript](https://stackoverflow.com/questions/10339506/how-to-perform-less-than-greater-than-comparisons-on-custom-objects-in-javascrip) – pilchard Aug 13 '23 at 08:36

2 Answers2

0

You can add the value of the letter to the number to make sure that the same numbers come in alphabetic order (here descending in letter order too)

If you want 'a',3 to come before 'b',3, then we need to sort on both entries

let arr=[['g',10000],['s',500],['b',3],['a',200],['a',1000],['a',3]]

arr.sort((a,b) => b[1]+b[0].charCodeAt(0) - a[1]+a[0].charCodeAt(0))

console.log(arr)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

First of all, the number in your sub-array is on the index 1 and you're using index 0.

Second, I made an ascendDescend function for my own use but never used it, hope it'll be helpful to you:

function ascendDecend(string) {
let arr = string.split(",");
arr.forEach((e, i, ar) => ar[i] = Number.parseFloat(e));

let decendingArr = [];

const minArr = [...arr];
for (let i = 0; i < arr.length; i++) {
    const minValue = Math.min(...minArr);
    const minIndex = minArr.indexOf(minValue);

    decendingArr.push(minValue);
    minArr.splice(minIndex, 1);
}


let ascendingArr = [...arr].map((e, i, arr) => {
    const pushable = Math.max(...arr);
    arr[arr.indexOf(pushable)] = "";
    return pushable;
});

return [ascendingArr, decendingArr];
}

change it as per your need, I made it for a string and not an array.