I am trying to write a function which would loop through a list of positions in an array(Position Array) and for each position create an array in the Position Array. And then loop through another array with candidates with different positions and sort them into the arrays with the same positions within the Position Array.
This is what I have been able to do, I want to be able to make it dynamic, but do not know how to go about it;
Here’s my code:
let positionArr = ["Chairman", "Secretary", "Organiser",
"Finacial Secretary" ];
let varPositions = [];
let candidates = [
{
name: "Kwesi",
position: "Finacial Secretary",
},
{
name: "Kofi",
position: "Chairman",
},
{
name: "Ama",
position: "Secretary",
},
{
name: "Kwame",
position: "Finacial Secretary",
},
{
name: "Juliet",
position: "Organiser",
},
{
name: "Jese",
position: "Chairman",
},
];
const sort = () => {
let position;
positionArr.forEach((element) => {
element = new Array();
varPositions.push(element);
});
candidates.forEach((elementPos) => {
position = elementPos.position;
positionArr.forEach((element) => {
if (element === position) {
if (position === positionArr[0]) {
varPositions[0].push(elementPos);
} else if (position === positionArr[1]) {
varPositions[1].push(elementPos);
} else if (position === positionArr[2]) {
varPositions[2].push(elementPos);
} else if (position === positionArr[3]) {
varPositions[3].push(elementPos);
}
}
});
});
console.log(varPositions);
};
sort();
Thanks in Advance 🙂
>Solution :
If all you’re trying to do is sort your candidates based on the positions array, it is much much simpler than you have there. You simply sort
by the index in the array
const result = candidates.sort((a,b) =>
positionArr.indexOf(a.position)
- positionArr.indexOf(b.position)
)
Live example:
let positionArr = ["Chairman", "Secretary", "Organiser",
"Finacial Secretary" ];
let candidates = [
{
name: "Kwesi",
position: "Finacial Secretary",
},
{
name: "Kofi",
position: "Chairman",
},
{
name: "Ama",
position: "Secretary",
},
{
name: "Kwame",
position: "Finacial Secretary",
},
{
name: "Juliet",
position: "Organiser",
},
{
name: "Jese",
position: "Chairman",
},
];
const result = candidates.sort((a,b) =>
positionArr.indexOf(a.position)
- positionArr.indexOf(b.position)
)
console.log(result);