简体   繁体   中英

return the smallest element in the array located in the given key

I wanted to return the smallest element in a given object and a key, but it should return undefined if the given array was empty or the property at the given key is not an array. I solved it, but I wasn't totally satisfied with my approach. Any suggestions to make my code shorter maybe?.

let obj = {
  key: [8, 5, 10, 15, 11, 21, 1, 25]
};

const smallest = (obj, key) => {
  return !Array.isArray(obj[key]) || obj[key].length <= 0 ? undefined : obj[key].reduce((l, s) => l < s ? l : s)
}
smallest(obj, 'key');

You could take the check and return the minimum value.

 const smallest = (obj, key) => Array.isArray(obj[key]) && obj[key].length ? Math.min(...obj[key]) : undefined; console.log(smallest({ key: [8, 5, 10, 15, 11, 21, 1, 25] }, 'key')); console.log(smallest({ key: [8] }, 'key')); console.log(smallest({ key: [] }, 'key')); console.log(smallest({}, 'key')); 

Instead of reduce you can use Math.min() with spread operator(...) on the array

 let obj = { key: [8, 5, 10, 15, 11, 21, 1, 25] }; const smallest = (obj, key) => { return !Array.isArray(obj[key]) || obj[key].length <= 0 ? undefined : Math.min(...obj[key]); } console.log(smallest(obj, 'key')); 

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