Home > Mobile >  How to find the lightest object
How to find the lightest object

Time:05-20

Hello how can I find the lightest object from array of objects. I do not want to get value, but the object with this value. Not for instance just 1200 but the object {mass: 1200, numberOfel: ..., indexOfEl: ... , isCorrect: boolean}

let massOfElephants = [2400, 2000, 1200, 2400, 1600, 4000];
let startOrder = [1, 4, 5, 3, 6, 2];
const elephantObject = [];
  
  startOrder.forEach((val, i) => {
    elephantObject.push({
      mass: massOfElephants[val - 1],
      numberOfEl: val,
      indexOfEl: i,
      isCorrect: false,
    });
  });

CodePudding user response:

Since you have a list of objects already, all you need to do is sort the objects according to their mass properties. The way to go about it is to write a custom comparator function which to sort by (See Array.prototype.sort()).

For numeric types, the comparator function (a,b) => a - b will sort the values increasingly, and myArray.sort((a, b) => a - b) will sort myArray accordingly.

After sorting elephantObject.sort((a,b) => a.mass - b.mass), the lightest elephant will be the first entry of your object array: elephantObject[0]. as

CodePudding user response:

The reduce method reduces an array to a single value using a callback function.

const getLightest = (initial, current){
    return (initial.mass < current.mass)?initial:current;
}
const lightest = elephantObject.reduce(getLightest);
  • Related