I want to convert an Array of Arrays to one object with the same sort in javascript. My problem is the keys are in numbers and i just sorted the values as i want but when i convert the array to object by useing reduce it sort it again by keys.
const names = {
1: 'ياسر',
3: 'احمد'
}
const sorting = Object.entries(names)
.sort((a, b) => a[1].localeCompare(b[1], "ar", { ignorePunctuation: true }))
.reduce((acc, x) {
acc[x[0]] = x[1];
return acc;
}, {});
Objects don't preserve order of insertion when keys parsed as integers. So you can only append a string to the keys or use Map instead.
const names = {
3: 'D',
7: 'A',
5: 'B',
8: 'C'
}
names["4"] = "E";
console.log("names", names);
const object = Object.entries(names)
.sort((a, b) => a[1].localeCompare(b[1], "ar", { ignorePunctuation: true }))
.reduce((acc, x) => {
acc[x[0]] = x[1];
return acc;
}, {});
console.log("as object", object);
const objectString = Object.entries(names)
.sort((a, b) => a[1].localeCompare(b[1], "ar", { ignorePunctuation: true }))
.reduce((acc, x) => {
acc["_" + x[0]] = x[1];
return acc;
}, {});
console.log("as object w/string", objectString);
const map = Object.entries(names)
.sort((a, b) => a[1].localeCompare(b[1], "ar", { ignorePunctuation: true }))
.reduce((acc, x) => {
acc.set(x[0], x[1]);
return acc;
}, new Map());
console.log("as map", map, "look in devtools");
[EDIT] There is a way utilize proxy, which will allow "hide" prefix of the keys:
const names = {
3: 'D',
7: 'A',
5: 'B',
8: 'C'
}
names["4"] = "E";
console.log("names", names);
function sortObject(obj)
{
const prefix = "___";
return new Proxy(
/* proxy target */
Object.entries(obj)
.sort((a, b) => a[1].localeCompare(b[1], "ar", { ignorePunctuation: true }))
.reduce((acc, x) => (acc[prefix + x[0]] = x[1], acc), {})
,
{ /* proxy handler */
get(target, key)
{
return typeof key == "string" ? target[prefix + key] : target[key];
},
set(target, key, value)
{
target[prefix + key] = value;
},
ownKeys: target => Object.keys(target).map(e => e.substring(prefix.length)), //remove prefix
getOwnPropertyDescriptor: (target, key) => ({ enumerable: true, configurable: true })
});
}
let proxy = sortObject(names);
proxy[0] = "AA"; //new properties added to the end
console.log("proxy added new entry to the end", proxy);
proxy = sortObject(proxy); //we can sort it again
console.log("proxy sorted with new entry", proxy);
console.log("it's enumerable too!");
for(i in proxy)
console.log("key:", i, "value:", proxy[i]);