I am figuring out if there is a better way to sort the below array.
The below code sorts the array based on the label and deviceRegistered. if label is Desk phone and deviceRegistered is true then it should take the precedence.
My approach is like below.
const terminals = [
{
"device":"JKJCF00",
"directory":" 1899990000",
"label":"Jabber",
"deviceRegistered":"false"
},
{
"device":"IOP8999",
"directory":"9099886644",
"label":"Desk Phone",
"deviceRegistered":"false"
},
{
"device":"KLJ7888",
"directory":" 8999999",
"label":"Jabber",
"deviceRegistered":"true"
},
{
"device":"VFD87987",
"directory":" 12386444",
"label":"Desk Phone",
"deviceRegistered":"true"
}]
let term = [...terminals],arr=[],sortedLines = [],lineObj ={};
term.forEach(line => arr.indexOf(line.label)===-1 ? arr.push(line.label):'');
arr.forEach(device => {
let filterArr = term.filter(line => line.label === device)
let sortArr = [...filterArr].sort((dev1,dev2) => dev1.deviceRegistered !== 'true' ? 1 : dev2.deviceRegistered !== 'true' ? -1 : 0)
lineObj[device] = sortArr
})
for (line in lineObj){ console.log(lineObj[line])
sortedLines.push(...lineObj[line])
}
}
The output is
[
{
"device":"KLJ7888",
"directory":" 8999999",
"label":"Jabber",
"deviceRegistered":"true"
},
{
"device":"JKJCF00",
"directory":" 1899990000",
"label":"Jabber",
"deviceRegistered":"false"
},
{
"device":"VFD87987",
"directory":" 12386444",
"label":"Desk Phone",
"deviceRegistered":"true"
},
{
"device":"IOP8999",
"directory":"9099886644",
"label":"Desk Phone",
"deviceRegistered":"false"
}
]
CodePudding user response:
You could check the properties and use the delta of the boolean values.
const
array = [
{ device: "JKJCF00", directory: " 1899990000", label: "Jabber", deviceRegistered: "false" },
{ device: "IOP8999", directory: "9099886644", label: "Desk Phone", deviceRegistered: "false" },
{ device: "KLJ7888", directory: " 8999999", label: "Jabber", deviceRegistered: "true" },
{ device: "VFD87987", directory: " 12386444", label: "Desk Phone", deviceRegistered: "true" }
];
array.sort((a, b) =>
(b.label === 'Desk Phone') - (a.label === 'Desk Phone') ||
(b.deviceRegistered === 'true') - (a.deviceRegistered === 'true')
);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
Assumption: I'm the author of this library, but I created sort-es exactly to simplify the array sorting.
If you're interested : docs GH
import { byValues, byString, byValue, byBoolean } from "sort-es"
const terminals = [] //...items
const sorted = terminals.sort(byValues([
["label", byString()],
["deviceRegistered", byValue(d => d === 'true', byBoolean())]
]))