skip to Main Content

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

2

Answers


  1. 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)
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search