简体   繁体   中英

Ranking a multidimensional array in javascript

I've been banging my head against this for a few days now and can't find a solution.

I have an array that looks like the following.

var myArr = [
[1, 10],
[0, 9],
[0, 8],
[0, 11],
[0, 12]
];

The data is a list of items for sale, the first element is a 0 if its not mine and a 1 for my item, the second element is the price.

From this I need to return the rank of the one with a 1 in it against the others [3/5] so I need to sort it by the second element then get the rank of the first element.

I've been trying to use this code to sort it

myArr.sort(function (a, b) {
   return a[0] - b[0];
});

Then this to find the rank

    function getIndexOfK(arr, k) {
        for (var i = 0; i < arr.length; i++) {
            var index = arr[i].indexOf(k);
            if (index > -1) {
                return [i, index];
            }
        }
    }

    var needle = 1;
    var result = getIndexOfK(competitorsArr, needle);
    console.log('The value #' + needle + ' is located at array[' + result[0] + '][' + result[1] + '].');

But it is returning this every time?

The value #1 is located at array[0][0].

Any pointers as to what I'm doing wrong?

Many Thanks,

Richard

so I need to sort it by the second element then get the rank of the first element.

Yep, but, in your code:

myArr.sort(function (a, b) {
  return a[0] - b[0];
});

you're sorting by the first element, not the second. Fix that, and it works fine:

 var myArr = [ [1, 10], [0, 9], [0, 8], [0, 11], [0, 12] ]; myArr.sort(function(a, b) { return a[1] - b[1]; }); function getIndexOfK(arr, k) { for (var i = 0; i < arr.length; i++) { var index = arr[i].indexOf(k); if (index > -1) { return [i, index]; } } } console.log(getIndexOfK(myArr, 1)); 

You could reduce the time complexity by identifying the price of your item, and then iterating over the array and checking how many items are cheaper, O(N) , no sorting required:

 var myArr = [ [1, 10], [0, 9], [0, 8], [0, 11], [0, 12] ]; const myPrice = myArr.find(([owner]) => owner === 1)[1]; const numCheaperThanMine = myArr.reduce( (a, [owner, price]) => ( price < myPrice && owner !== 1 ? ++a : a ), 0 ); console.log(numCheaperThanMine); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM