devdropper87
devdropper87

Reputation: 4187

nodejs writeFile returning duplicates

I have written the following nodejs script (sortLabels.js), and it works fine for the file at labelsFilePath, which containts object, but it doesn't work for the file at labelIdsFilePath which is an array of strings. I am basically trying to sort both files and then overwrite the contents of those files with the newly sorted values. For some reason, in the labelIds file, I get duplicates.

let labelsFilePath = './server/mocks/label.json';
let labels = require(labelsFilePath);
let labelIdsFilePath = './client/app/common/config/label-ids.json';
let labelIds = require(labelIdsFilePath);
const _ = require('lodash');
let fs = require('fs');

labels = _.sortBy(labels, "id"); 
labelIds = _.sortBy(labelIds, (num) => num);

fs.writeFile(labelsFilePath, JSON.stringify(labels), function(err){
  if(err) console.log(err); else {
    console.log('labels were sorted');
  }
})

fs.writeFile(labelIdsFilePath, JSON.stringify(labelIds), function(err){
  if(err) console.log(err);
  else {
    console.log('labels ids were sorted');
  }
})

before running the script (node sortLabels), this is what labelIds look like:

 [
  "0083",
  "0117",
  "0021",...]

and after:

["0012","0012","0021","0021"....]

what am I doing wrong/missing?

Upvotes: 0

Views: 535

Answers (1)

frankleonrose
frankleonrose

Reputation: 365

Since the result of the execution is a well formed JSON object in labelIdsFilePath, it seems that everything is working right.

Perhaps the original set of numbers includes duplicates and sorting them is making that fact more transparent?

Try printing out the length of the array before and after it sorts it. That should demonstrate to you that it isn't doubling the size, you're just seeing duplicates that are there.

console.log(labelIds.length)

If you really don't need the duplicates,

labelIds = _.uniq(labelIds)

and THEN save it.

Upvotes: 1

Related Questions