如何在数组中查找包含最大值的对象

时间:2019-01-11 09:55:39

标签: javascript

我正在使用一个库来预测用户在网络摄像头前的情绪。有四种情绪:愤怒,悲伤,惊讶和快乐。我想检查哪种情绪得分最高。当我console.log预测情感时,我看到以下内容:

(4) [{…}, {…}, {…}, {…}]
 0: {emotion: "angry"value: 0.08495773461377512}
 1: {emotion: "sad", value: 0.05993173506165729}
 2: {emotion: "surprised", value: 0.054032595527500206}
 3: {emotion: "happy", value: 0.18562819815754616}

关于如何获得最高价值的情感的任何想法?

3 个答案:

答案 0 :(得分:5)

您可以缩小数组并采用具有最高值的对象。然后采取物体的情感。

var data = [{ emotion: "angry", value: 0.08495773461377512 }, { emotion: "sad", value: 0.05993173506165729 }, { emotion: "surprised", value: 0.054032595527500206 }, { emotion: "happy", value: 0.18562819815754616 }],
    highest = data
        .reduce((a, b) => a.value > b.value ? a : b)
        .emotion;
    
console.log(highest);

答案 1 :(得分:2)

我将使用reduce

const highest = arr.reduce((a, b) => a.value > b.value ? a : b, {});
console.log(highest);
<script>
const arr = [
    {
        emotion: "angry",
        value: 0.08495773461377512
    },
    {
        emotion: "sad",
        value: 0.05993173506165729
    },
    {
        emotion: "surprised",
        value: 0.054032595527500206
    },
    {
        emotion: "happy",
        value: 0.18562819815754616
    }
];
</script>

或者您可以使用sort(但由于性能我宁愿减少)

arr.sort((a, b) => b.value - a.value);
console.log(arr[0]);
<script>
    const arr = [
        {
            emotion: "angry",
            value: 0.08495773461377512
        },
        {
            emotion: "sad",
            value: 0.05993173506165729
        },
        {
            emotion: "surprised",
            value: 0.054032595527500206
        },
        {
            emotion: "happy",
            value: 0.18562819815754616
        }
    ];
    </script>

答案 2 :(得分:0)

const data = [
            {emotion: "angry", value: 0.08495773461377512},
            {emotion: "sad", value: 0.05993173506165729},
            {emotion: "surprised", value: 0.054032595527500206},
            {emotion: "happy", value: 0.18562819815754616}
        ],
        highest = process(data);

    function process(data) {
        return data.sort(function (a, b) {
            return b.value - a.value;
        });
    }

    console.log("highest==>",highest,"sorted-array ==>",data[0].emotion);