Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find lowest value in nested array in javascript

Tags:

javascript

i am trying to find the name with the lowest number after it, but iterating over it is slow with larger lists. For exaple the expected output should be ["bob", 1] ["jeff", 2] ["wal-E",2]

let items = [["bob",1],["jeff",2],["wal-E",2],["bob",1],["bob",10]]
let items2 = []
let Lowest = 0;
for (y in items){
    for (z in items)
      {
        if (items[y][0] == items[z][0] && items[y][1]<=items[z][1]){
          continue;
        } else if (items[y][0] == items[z][0]){
            Lowest += 1
            if (Lowest >= 2){
            break;
            }
            else {
            continue;
            }
        }
        }      
  if (Lowest == 0){
    items2.push(items[y])
  }
}
console.log(items2);
like image 434
Samuel Liebert Avatar asked Dec 19 '25 16:12

Samuel Liebert


1 Answers

Using reduce is an elegant solution to acheive this

let items = [["bob",1],["jeff",2],["wal-E",2],["bob",1],["bob",10]];

const lowestItem = items.reduce((a, b) => a[1] < b[1] ? a : b);

console.log(lowestItem);

Read more about Array.prototype.reduce here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

like image 78
Ran Turner Avatar answered Dec 21 '25 05:12

Ran Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!