简体   繁体   中英

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:

(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

 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)

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

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