Home > Mobile >  Getting information from an Array with Strings and Integer Values as Strings by Size of Integer Valu
Getting information from an Array with Strings and Integer Values as Strings by Size of Integer Valu

Time:02-10

Let's say you have an array that looks like this:

arr = ['Steve', '80000', 'Jen', '90000', 'Bob', '40000']

Where arr[0] and arr[2] are the names of employees and arr[1] and arr[3] are their salaries.

How would you go about writing a function that would return the name of the person with the largest salary?

In the example above we'd look for the function to return 'Jen' because she has the highest salary.

My initial thought would be to turn all the values in the array to integers using parseInt(), finding the maximum value and then pointing to the value of the index before that maximum value but am having trouble writing a correct solution for this. Any help would be greatly appreciated!

CodePudding user response:

A simple linear scan using a for loop. Note I'm skipping 2 values in the for loop to catch only the numbers. If the max value is that position i then the respective user is at i-1

arr = ['Steve', '80000', 'Jen', '90000', 'Bob', '40000']

let tempMax = 0;
let result;
for(let i = 1; i<arr.length; i =2){
    if(tempMax<parseInt(arr[i])){
    tempMax = parseInt(arr[i]);
    result = arr[i-1]
  }
}

console.log(result)

CodePudding user response:

Chunk function

Object.defineProperty(Array.prototype, 'chunk', {value: function(n) {
    return Array.from(Array(Math.ceil(this.length/n)), (_,i)=>this.slice(i*n,i*n n));
}});

Then we can easily process [Name, Salary] pairs like,

["a", "11", "b", "12", "c", "3"]
  .chunk(2)
  .sort((p1, p2) => parseInt(p2) - parseInt(p1))[0]
  • Related