devdropper87 devdropper87 - 14 days ago 4x
Node.js Question

nodejs writeFile returning duplicates

I have written the following nodejs script (sortLabels.js), and it works fine for the file at

, which containts object, but it doesn't work for the file at
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:


and after:


what am I doing wrong/missing?


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.


If you really don't need the duplicates,

labelIds = _.uniq(labelIds)

and THEN save it.