简体   繁体   English

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

[英]How to find the object containing the highest value in an array

I'm using a library that predicts the emotion of the user in front of the webcam. 我正在使用一个库来预测用户在网络摄像头前的情绪。 There are four emotions: angry, sad, surprised and happy. 有四种情绪:生气,悲伤,惊讶和快乐。 I want to check which emotion has the highest score. 我想检查哪种情绪得分最高。 When i console.log predictedEmotions I see this: 当我在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}

Any ideas on how to get the emotion with the highest value? 关于如何获得最高价值的情感的任何想法?

You could reduce the array and take the object with the highest value. 您可以减少数组并获取具有最高值的对象。 Then take take the emotion of the object. 然后采取对象的情感。

 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); 

I'd use reduce 我会用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> 

Or you could use sort (but I'd prefer reduce because of performance) 或者你可以使用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> 

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM