I have an array of objects(product list), and I am implementing the sorting logic to it. In order to make it a single source of truth, I made a id-product map, which looks something like this:
const prodsMap = {
1 : {
id : 1,
name : 'abc',
price : 4
},
2 : {
id : 2,
name : 'aac',
price : 3
}
}
Now in order to sort products I am doing this:
function sortString(data, propName) {
return data.sort((obj1, obj2) => {
const val1 = obj1[propName]
const val2 = obj2[propName]
if (val1 < val2) {
return -1
}
if (val1 > val2) {
return 1
}
return 0
})
}
Calling the function like this:
const prods = sortString(Object.values(prodsMap), 'name')
Everything works fine here, the result of sorting will be an array of objects, in order to get the id's I am using map function.
Now the problem is that I've to iterate thrice(first to get object values, second to sort and third time to map id's), I was wondering if there is a better way to get only ID's when the array gets sorted.
and third time to map id'sBut thekeysare already theids..? (if they aren't, consider converting to an object structure so that they are)sortStringreturns array of objects, so keys won't be there anymore.sortmutates the array.sortStringreturns the sortedObject.keys(prodsMap). But the keys are the IDs, not objects. You're not sorting an array of objects, you're sorting an array of keys. (you don't even have an array of objects anywhere here)Object.keyswill always returns a new list and that list is passed to sorter.