I have 2 arrays.
The first array consists of 4 category objects, each containing a "name" and "ref"(reference):
let categories = [
{
"name": "Books",
"ref": "categories/category1"
},
{
"name": "Computers",
"ref": "categories/category2"
},
{
"name": "Drinks",
"ref": "categories/category3"
},
{
"name": "Food",
"ref": "categories/category4"
}
];
The second array contains references to categories:
let refs = ["categories/category2", "categories/category4"];
My goal is to create a new array of category names by extracting only the category names from the first array's "categories" variable using the references in the second array's "refs" variable.
I have successfully written code that accomplishes this task by iterating through both arrays and creating a new array with only the desired category names:
let newArr = [];
for(let i = 0; i < refs.length; i++) {
for(let j = 0; j < categories.length; j++) {
if(refs[i] == categories[j].ref) {
newArr.push(categories[j].name);
}
}
}
console.log(newArr); // ["Computers", "Food"]
This is the complete, executable code:
let categories = [
{
"name": "Books",
"ref": "categories/category1"
},
{
"name": "Computers",
"ref": "categories/category2"
},
{
"name": "Shoes",
"ref": "categories/category3"
},
{
"name": "Food",
"ref": "categories/category4"
}
];
let refs = ["categories/category2", "categories/category4"];
let newArr = [];
for(let i = 0; i < refs.length; i++) {
for(let j = 0; j < categories.length; j++) {
if(refs[i] == categories[j].ref) {
newArr.push(categories[j].name);
}
}
}
console.log(newArr); // ["Computers", "Food"]
However, I am seeking ways to simplify this code. Is there a more efficient way to achieve the same result?
let newArr = [];
for(let i = 0; i < refs.length; i++) {
for(let j = 0; j < categories.length; j++) {
if(refs[i] == categories[j].ref) {
newArr.push(categories[j].name);
}
}
}
console.log(newArr); // ["Computers", "Food"]