Javascript从和对象中找到具有最小(或最大)值的n个键

时间:2019-02-24 12:25:22

标签: javascript ecmascript-6 javascript-objects

我有一个像这样的javascript对象。给定一个数字n,如何获得具有最小和最大值的n键?

let obj = {
  "1632": 45,
  "1856": 12,
  "1848": 56,
  "1548": 34,
  "1843": 88,
  "1451": 55,
  "4518": 98,
  "1818": 23,
  "3458": 45,
  "1332": 634,
  "4434": 33
};

3 个答案:

答案 0 :(得分:3)

您可以sort Object.entries返回的键值对数组,并像这样获得第一个n键:

let obj={"1632":45,"1856":12,"1848":56,"1548":34,"1843":88,"1451":55,"4518":98,"1818":23,"3458":45,"1332":634,"4434":33};

const n = 5;

const smallestNKeys = Object.entries(obj)
                            .sort((a, b) => a[1] - b[1])
                            .slice(0, n)
                            .map(a => a[0])

console.log(smallestNKeys)

或遍历keys以避免额外的map

let obj={"1632":45,"1856":12,"1848":56,"1548":34,"1843":88,"1451":55,"4518":98,"1818":23,"3458":45,"1332":634,"4434":33};

const n = 5;

const smallestNKeys = Object.keys(obj)
                            .sort((a, b) => obj[a] - obj[b])
                            .slice(0, n)

console.log(smallestNKeys)

由于您提到了最小或最大,因此您可以创建一个接受order参数的函数。然后根据该参数,您可以在sort的compareFunction回调中乘以1或-1。

let obj={"1632":45,"1856":12,"1848":56,"1548":34,"1843":88,"1451":55,"4518":98,"1818":23,"3458":45,"1332":634,"4434":33};

getSortedKeys = (obj, n, order) => {
  const multiplier = order === "asc" ? 1 : -1;
  
  return Object.keys(obj)
                .sort((a, b) => multiplier * (obj[a] - obj[b]))
                .slice(0, n)
}

console.log(getSortedKeys(obj, 3, "desc"))
console.log(getSortedKeys(obj, 5, "asc"))

答案 1 :(得分:0)

这是用于查找n个最小值的键的代码。要将其更改为最大键,请将第三行中的<更改为>

const smallestkeys = (obj, n = 1) =>
    Object.keys(obj).reduce((keyArr, k, i) =>
        (!i || obj[k] < obj[keyArr[keyArr.length - 1]])
            ? [k, ...keyArr].slice(0, n).sort((a, b) => obj[a] - obj[b])
            : keyArr
        , []);

答案 2 :(得分:0)

您可以使用Object.entriessortreduce

let obj = { "1632": 45, "1856": 12, "1848": 56, "1548": 34, "1843": 88, "1451": 55, "4518": 98, "1818": 23, "3458": 45, "1332": 634, "4434": 33 };

let findNkeys = 
    (input,n) => Object.entries(input)
                 .sort(([,A],[,B])=>A-B)
                 .reduce((op,[key],index)=>( index < n ? op.push(key) : op, op),[])

console.log(findNkeys(obj,2))