简体   繁体   English

获取对象数组的 5 个最高条目 - Javascript

[英]Get 5 highest entries of object array - Javascript

Yesterday I got my extraction from a csv working but now ran into another wall.昨天我从一个 csv 工作中提取出来,但现在遇到了另一堵墙。 Basically I now have an array of objects with the properties Name, Score and Kills.基本上我现在有一组具有名称、分数和杀戮属性的对象。

I now want to take out 5 objects that have the highest amount of points and sort them from the highest to the lowest of these 5. For now I only have 4 entries as only 4 individuals connected to the server but I want to already get it to work for the future.我现在想取出 5 个具有最高点数的对象,并将它们从这 5 个中的最高到最低进行排序。现在我只有 4 个条目,因为只有 4 个连接到服务器的人,但我想已经得到它为未来工作。

heres my current code :继承人我目前的代码:

const csv = require('csv-parser');
const fs = require('fs');

fs.createReadStream('./FFA/csv/rankme.csv')
.pipe(csv({ delimiter: ',', from_line: 2 }))
.on('data', (row) =>
 {
  const keyLookup = ['name', 'score', 'kills'];

const newData = Object.keys(row)
  .filter(key => keyLookup.includes(key))
  .reduce((obj, key) => {
    obj[key] = row[key];
    return obj;
  }, {});

console.log(newData);

  });

and this is the output on the console :这是控制台上的输出:

{ name: 'liHi-', score: '998', kills: '1' }
{ name: 'xyCe', score: '1004', kills: '3' }
{ name: 'Лови Аптечка Брат', score: '1000', kills: '0' }
{ name: 'buronhajredini108', score: '1000', kills: '0' }

Here: You sort it.在这里:你排序。 Then wth .slice() you copy the first 5 elements from the sorted array.然后使用.slice()从排序数组中复制前 5 个元素。

In this example i am taking only 3 out.在这个例子中,我只取出 3 个。 You can ofcorse change the value.您可以 ofcorse 更改该值。 The 0 means it starts from index 0 and slices 3 items out from index 0 0表示它从索引 0 开始并从索引 0 中切出 3 个项目

 const csv = require('csv-parser'); const fs = require('fs'); let data = []; fs.createReadStream('./FFA/csv/rankme.csv') .pipe(csv({ delimiter: ',', from_line: 2 })) .on('data', (row) => { const keyLookup = ['name', 'score', 'kills']; const newData = Object.keys(row) .filter(key => keyLookup.includes(key)) .reduce((obj, key) => { obj[key] = row[key]; return obj; }, {}); data.push(newData); }) .on("close", () => { let sorted = data.sort((a,b) => b.score - a.score).slice(0,3) console.log(sorted); })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM