Reputation: 15
I'm trying to figure out the best way to take an element, compare it to elements in an existing array and if that returns true, push that element into another array with the same index.
I currently have an array but it needs to appear in a certain order so what I've done is created an array with the order it needs to be in. I thought about creating an object where each value of the key is an array and push the elements into the array with is equal to the key but not sure if that's the best way to go about it.
This is the code I am currently working with :
let categories = [];
const categoryOrder = [
"Headings",
"Text",
"Lists & Menus",
"Quotes",
"Banners",
"Images",
"Videos",
"Galleries",
"Logos",
"Clickthrough Images",
"Buttons & CTAs",
"Lines & Dividers",
"Actions",
"Social Media & Integrations",
"Blog, Events & Podcast",
"Ecommerce",
"Navigation",
"Footers",
"Premium",
"Misc",
];
defaultComponents &&
defaultComponents.forEach((component) => {
categories.push(component.category);
});
categories = [...new Set(categories)];
Hope this makes sense.
Upvotes: 1
Views: 931
Reputation: 4597
If the data that is present in the defaultComponents
does not already have the order that you want, or you only get a subset of the categories that your categoryOrder
array has, then you could do something like this:
const categories = defaultComponents.map((c) => c.category);
categories.sort((a, b) => {
const aIndex = categoryOrder.indexOf(a);
const bIndex = categoryOrder.indexOf(b);
return aIndex === bIndex ? 0 : aIndex < bIndex ? -1 : 1;
});
Upvotes: 0
Reputation: 11541
Array.map
allows you to map an existing Array to another one by transforming each element
const newArray = originalArray.map(value => {
if (condition(value)) {
return newValue
}
})
The index will be preserved, and you'll get undefined values when the condition is not truthy
Upvotes: 1