简体   繁体   中英

Manipulating Javascript array of objects

I have an array of objects and need to create a new array which contains the values of a specific key within the objects. Is there a more elegant way than the following code (note: without using anything more than JQuery). Expected result is: 455, 387, 495

var arr=[{sid:387,rank:2},{sid:455,rank:1},{sid:364,rank:4},{sid:495,rank:3}];
var topThreeTemp = arr.filter(function(a){return a.rank<4;}).sort(function(a,b){return a.rank>b.rank;});
var topThreeSIDs=[];
for(var i=0;i<topThreeTemp.length;i++){
    topThreeSIDs.push(topThreeTemp[i].sid);
}
console.log(topThreeSIDs.join(", "));

Use ES6 map , instead of for and ES6 arrow functions (syntax sugars):

 const arr = [ { sid: 387,rank: 2 }, { sid: 455,rank: 1 }, { sid: 364,rank: 4 }, { sid: 495,rank: 3 } ] const topThreeSIDs = arr .filter(({ rank }) => rank < 4) .sort((a, b) => a.rank > b.rank) .map(({ sid }) => sid) console.log(topThreeSIDs.join(', ')) 

You could filter, sort with delta, slice and map sid as result array.

 var array = [{ sid: 387, rank: 2 }, { sid: 455, rank: 1 }, { sid: 364, rank: 4 }, { sid: 495, rank: 3 }], top3 = array .filter(({ rank }) => rank < 4) .sort((a, b) => a.rank - b.rank) .slice(0, 3) .map(({ sid }) => sid); console.log(top3.join(", ")); 

Use Array.map

 var arr=[{sid:387,rank:2},{sid:455,rank:1},{sid:364,rank:4},{sid:495,rank:3}]; var result = arr.filter(({rank}) => rank < 4).sort((a,b) => a.rank > b.rank).map(({sid}) => sid); console.log(result.join(", ")); 

function pluck(objs, name, condition) {
        var sol = [];
        for (var i in objs) {
            if (objs[i].hasOwnProperty(name) && condition && condition(objs[i])) {
                // console.log(objs[i][name]);
                sol.push(objs[i][name]);
            }
        }
        return sol;
    }

    var arr = [{sid: 387, rank: 2}, {sid: 455, rank: 1}, {sid: 364, rank: 4}, {sid: 495, rank: 3}];
    var pluckedArray = pluck(arr, sid, function (item) {
        return item.rand < 4; // your custom condition
    })

How about iterate the array only once, and build the resultant array?

arr.reduce((r, {rank, sid})=>(rank < 4 && (r[rank -1] = sid), r), [])

 var arr = [{ sid: 387, rank: 2 }, { sid: 455, rank: 1 }, { sid: 364, rank: 4 }, { sid: 495, rank: 3 }], top3 = arr.reduce((r, {rank, sid})=>(rank < 4 && (r[rank -1] = sid), r), []); console.log(top3); 

Note: When you need top 3 within highest rank 4 and also know ranks are unique, you can use this. If ranks are not unique you can use r.splice(rank-1, 0, sid) instead of r[rank-1] = sid and slice top 3 at the end.

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