Last active
July 19, 2023 06:01
-
-
Save VenkateswaraT/3a205b33ce41ac587f11f45fe2c65935 to your computer and use it in GitHub Desktop.
Categorical Sort in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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