I am currently working with JSON data and facing a sorting issue. The data structure looks like this:
[
{
"name" : "",
"location" : "home"
},
{
"name" : "",
"location" : "office"
}
]
However, I am unable to sort this data using a function compare(a,b). Due to the JSON format, I cannot call data.sort(compare) as I would if it was in a different format.
I have attempted to read the data from a .json file using the FS module:
let data = fs.readFileSync('./app/data/testData.json');
My goal is to sort the data based on the 'location' key in alphabetical order. Although I've tried implementing the suggested solution involving the compare function, the data remains unsorted.
Is there a way to convert my JSON data into a different format that allows me to use the compare function for sorting?
Here's the code snippet I've tried based on the provided solution:
function compare(a,b) {
if (a.location < b.location)
return -1;
if (a.location > b.location)
return 0;
return 0;
}
let dataSort = fs.readFileSync('./app/data/testData.JSON');
let dataParse = JSON.parse(dataSort);
dataParse.sort(compare);
console.log(dataParse);
Despite these efforts, the data set remains unchanged after sorting by location.