1

I am trying to write a function that accepts an array of maps and a key and returns the minimum value associated with the given key. For example,

minKeyVal([{ a: 1, b: 4 }, { a: 2, b: 6 }, { a: 3, b: 1 }], 'b'); //should return 1. 

I can get this to work outside of a function as follows:

//sample array of maps
const originalArray = [
  { a: 1, b: 4 },
  { a: 2, b: 6 },
  { a: 3, b: 1 },
];
 
//select values by a specific key
const newArray = originalArray.map(object => object.b);

//in the new array of B values, iterate through to find the min
var res = newArray[0];
for(let i = 1; i < newArray.length; i++) {
  if(newArray[i] < res){
      res = newArray[i]
  }
}

//print result
console.log(res);

// 1 is returned

When I have attempted to create a function based on this logic, I have not been successful. This is my latest attempt, which returns undefined:

function minKeyVal (originalArray, id) {
  const newArray = originalArray.map(object => object.id);

  var res = newArray[0];
  for(let i = 1; i < newArray.length; i++) {
    if(newArray[i] < res){
        res = newArray[i]
    }
    return res;
  }
}
console.log(minKeyVal([
    { a: 1, b: 4 },
    { a: 2, b: 6 },
    { a: 3, b: 1 },
  ], 'b'));

Help, hints and suggestions all welcome! I'd actually prefer suggestions of what to try or resources that might guide me so I can continue to work through it :)

J. Fede
  • 13
  • 2

3 Answers3

3

You could map an array with the wanted key and get the minimum of it.

const
    minKeyVal = (array, key) => Math.min(...array.map(o => o[key]));

console.log(minKeyVal([{ a: 1, b: 4 }, { a: 2, b: 6 }, { a: 3, b: 1 }], 'b'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Use Array.reduce() to convert an array to a single value:

const minKeyVal = (originalArray, id) => 
  originalArray.reduce((acc, item) => acc < item[id] ? acc : item[id], Infinity)
  
const result = minKeyVal([{"a":1,"b":4},{"a":2,"b":6},{"a":3,"b":1}], 'b')

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

It's because you always look up the 'id' property (literally) because of the . accessor syntax, and not the property named the value of the id variable.

Change it into a dynamic key lookup ([] accessor syntax):

function minKeyVal (originalArray, id) {
  const newArray = originalArray.map(object => object[id]);

  var res = newArray[0];
  for(let i = 1; i < newArray.length; i++) {
    if(newArray[i] < res){
        res = newArray[i]
    }
    return res;
  }
}
FZs
  • 16,581
  • 13
  • 41
  • 50