简体   繁体   中英

How do I extract variables from an array based on their value?

I stored variables in an array. Now I need to extract the variables with the highest value and store them in another array.

This is for a javascript program running on a wix website for my daughter.

var kiara = 1;
var rodeo = 3;
var calypso = 3;
var balthazar = 3;
var mistral = 4;
var saya = 4;
var luna = 4;

var points = [{kiara}, {rodeo}, {calypso}, {balthazar}, {mistral}, {saya}, {luna}],

The variables are already in ascending order. So I need the program to figure out that mistral, saya and luna tied at the top position, then to extract these 3 variables (name of the variables + respective values) and store them in another array. If I had a case where a single variable had the highest value, then a single variable would be stored in the new array.

Since your array is ordered, you already know the maximun value is at the last position of the array. So first, you can get this value, and then you can use this value to filter elements whose values are equal to this one:

 var kiara = 1; var rodeo = 3; var calypso = 3; var balthazar = 3; var mistral = 4; var saya = 4; var luna = 4; var points = [{kiara}, {rodeo}, {calypso}, {balthazar}, {mistral}, {saya}, {luna}]; // Since array is ordered, highest value is at the last position. // So, we can get it like this: let maxVal = Object.values(points[points.length - 1])[0]; console.log(maxVal); // Now, filter the array with the highest elements let highest = points.filter(x => Object.values(x)[0] === maxVal); console.log(highest)

In the case your initial array is not ordered as you have mentioned, then you can proceed with something like this:

 var kiara = 1; var rodeo = 3; var calypso = 3; var balthazar = 3; var mistral = 4; var saya = 4; var luna = 4; var points = [{saya}, {rodeo}, {mistral}, {balthazar}, {luna}, {kiara}, {calypso}]; // Since array is not ordered, we need to get highest value. // So, we can get it like this: let maxVal = points.reduce((max, v) => Math.max(Object.values(v)[0], max), null); console.log(maxVal); // Now, filter the array with the highest elements let highest = points.filter(x => Object.values(x)[0] === maxVal); console.log(highest)

One way is to find the biggest value first with .map and .reduce working together. Then we can get the objects from the points array that have their first properties with value of maxValue and push it to a separate array newArray .

var maxValue = points
    .map(function(obj){ return obj[Object.keys(obj)[0]]; }) //map into array of numbers
    .reduce(function(a, b){ return Math.max(a, b);}); // return max value

var newArray = points // filter objects with first prop = maxValue
    .filter(function(obj){ return obj[Object.keys(obj)[0]] === maxValue; });

Result will be: [{mistral: 4}, {saya: 4}, {luna: 4}]

Solution Below. There would be a way to do this with less code, but this will get the job done for you. One thing to remember, for in loops are your friend when working with objects.

var kiara = 1;
var rodeo = 3;
var calypso = 3;
var balthazar = 3;
var mistral = 4;
var saya = 4;
var luna = 4;

var points = [{rodeo}, {calypso}, {balthazar}, {mistral}, {saya}, {luna},{kiara}];

var maxNumberArray = [];
var maxNamesArray = []; // ADDED THIS LINE
var max;

for(var char in points){
    for(var name in points[char]){
        if(!max){
            max = points[char][name];
        } else {
            if(max < points[char][name]){
                max = points[char][name];
            }
        }
    }
}

for(var char in points){
    for(var name in points[char]){
        if(points[char][name] === max){
            maxNumberArray.push(points[char]);
            maxNamesArray.push(name); // ADDED THIS LINE
        }
    }
}



console.log(JSON.stringify(maxNumberArray));
console.log(maxNamesArray); // ADDED this LINE

:)

Here is the ES6 way of doing things. The edge case of the list not being in order is taken care of, so the highest values can be anywhere. You can also modify it to get the smallest values. If you have any questions about the code just ask and I will respond.

 const kiara = 1; const rodeo = 3; const calypso = 3; const balthazar = 3; const mistral = 4; const saya = 4; const luna = 4; function getNamesWithHighestPoints(points) { const hash = {}; for(let i = 0; i < points.length; i++) { let point = points[i]; let name = Object.keys(point)[0]; let score = Object.values(point)[0]; if(hash[score] === undefined) { hash[score] = [point]; } else { hash[score].push(point); } } let biggestScore = 0; Object.keys(hash).forEach(pointKey => { if(biggestScore < pointKey) { biggestScore = pointKey; } }); return hash[biggestScore]; } const points = [{kiara}, {rodeo}, {calypso}, {balthazar}, {mistral}, {saya}, {luna}]; console.log(getNamesWithHighestPoints(points));

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