Suppose we have an array of objects and we want it to move some objects with a certain property to the beginning of the array, For more clarity I will give an example:
let arr = [
{id:5 , tag: "X" , name:"mohsen"},
{id:1 , tag: "A" , name:"hasan"},
{id:3 , tag: "P" , name:"ali"},
{id:8 , tag: "D" , name:"mehran"},
{id:4 , tag: "C" , name:"nima"},
{id:12 , tag: "A" , name:"keivan"},
{id:6 , tag: "P" , name:"pedram"},
{id:17 , tag: "X" , name:"masoud"},
{id:20 , tag: "D" , name:"hadi"},
];
at this moment if we want to move objects with tag:"P"
to beginning of array like below:
[
{id: 3 ,name: "ali",tag: "P"},
{id: 6,name: "pedram",tag: "P"},
{id: 5,name: "mohsen",tag: "X"},
{id: 1,name: "hasan",tag: "A"},
{id: 8,name: "mehran",tag: "D"},
{id: 4,name: "nima",tag: "C"},
{id: 12,name: "keivan",tag: "A"},
{id: 17,name: "masoud",tag: "X"},
{id: 20,name: "hadi",tag: "D"}
]
What should we do?
for more description, at the first we map on array then for every item of array we check that
item[propName] === propValue
condition if it is true then we cut this item from its place withconst b = arr.splice(index , 1);
and put it at beginning of array witharr.splice(place,0,...b);
, theplace
variable track new index of beginning of array.