简体   繁体   中英

I want to set rank to array value?

I tried to create new array object from array, set rank according to its value. If value is the same, set the same rank and if next value is different set rank by skipping same rank length.

Expected result is

[ { "rank": 1, "data": 45 }, { "rank": 2, "data": 33 }, { "rank": 3, "data": 8 }, { "rank": 4, "data": 5 }, { "rank": 4, "data": 5 }, { "rank": 6, "data": 2 } ]

 var data = [8,5,2,33,5,45]; var rankList = []; var uniqueList = []; var rank = 0; var sameRank = 0; data.sort(function(a,b) { return b - a; }); for(var i in data) { if(uniqueList.includes(data[i])) { rank++; rankList.push({rank: sameRank, data: data[i]}); continue; } rank++; sameRank++; rankList.push({rank: rank, data: data[i]}); } console.log(rankList);

Once you've sorted the array, create another array of objects with .map , keeping track of the last rank and data used. If the new data is the same, use the same rank (the one taken from a prior iteration) - otherwise, use the current iteration index plus 1:

 const data = [8, 5, 2, 33, 5, 45]; data.sort((a, b) => b - a); let lastRank = 0; let lastData; const output = data.map((data, i) => { const objToReturn = { data }; objToReturn.rank = data === lastData? lastRank: i + 1; lastData = data; lastRank = objToReturn.rank; return objToReturn; }); console.log(output);

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