Skip to content

Instantly share code, notes, and snippets.

@VenkateswaraT
Last active July 19, 2023 06:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VenkateswaraT/3a205b33ce41ac587f11f45fe2c65935 to your computer and use it in GitHub Desktop.
Save VenkateswaraT/3a205b33ce41ac587f11f45fe2c65935 to your computer and use it in GitHub Desktop.
Categorical Sort in JavaScript
let array = [
{id: 0, type: "Office" },
{id: 1, type: "Security" },
{id: 2, type: "Office" },
{id: 3, type: "Security" },
{id: 4, type: "Security" },
{id: 5, type: "Office" },
{id: 6, type: "Agent" },
{id: 7, type: "Security" },
{id: 8, type: "Venkat" }
];
const order = ["Office", "Agent", "Security"];
for(let a of array){
if(order.indexOf(a.type)==-1){
order.push(a.type);
}
}
array.sort((a,b)=>order.indexOf(a.type)-order.indexOf(b.type));
// console.log(array);
let initialArray =['A','D', 'Z','A','D', 'Z','G','C','G'];
let categoryOrder=['Z','A','D','C'];
function customSort(initialArray, categoryOrder){
console.log(categoryOrder);
for(let a of initialArray){
if(categoryOrder.indexOf(a)==-1){
console.log('true',a);
categoryOrder.push(a);
}else{
console.log('false',a);
}
}
console.log(categoryOrder);
initialArray.sort((a,b)=>categoryOrder.indexOf(a)-categoryOrder.indexOf(b));
return initialArray;
}
customSort(initialArray,categoryOrder);
initialArray.sort()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment