1

Yesterday I got my extraction from a csv working but now ran into another wall. 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.

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' }

1 Answer 1

3

Here: You sort it. Then wth .slice() you copy the first 5 elements from the sorted array.

In this example i am taking only 3 out. You can ofcorse change the value. The 0 means it starts from index 0 and slices 3 items out from index 0

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);
})

Sign up to request clarification or add additional context in comments.

3 Comments

Can I also add this to the code without having to declare data manually ? So it takes out the info of the csv and immediately sorts it
@xyCe you need to push your newData witch is an object into an array and then filter it
Thank you so much I am very new to js and I'm getting lost so easily :b

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.