Create a fresh array by retrieving every value from every object in the initial array based on the pointers in the second array (JavaScript)

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"]

Answer №1

Utilize the filter method to extract categories with matching refs from an array.

If you solely require the names, consider employing the map function.

let categories = [
  { "name": "Book", "ref": "categories/category1" },
  { "name": "Computer", "ref": "categories/category2" },
  { "name": "Shoes", "ref": "categories/category3" },
  { "name": "Food", "ref": "categories/category4" }
];

let refs = ["categories/category2", "categories/category4"];

let filtered = categories.filter((c) => refs.includes(c.ref));
console.log(filtered);
// [{name: "Computer", ref: "categories/category2"}, {name: "Food", ref: "categories/category4"}]

let onlyNames = filtered.map((c) => c.name);
console.log(onlyNames);
// ["Computer", "Food"];

Answer №2

If you want to streamline your code, consider using the functions "map()" and "find()":

let categories = [
  { "name": "Book", "ref": "categories/category1" },
  { "name": "Computer", "ref": "categories/category2" },
  { "name": "Shoes", "ref": "categories/category3" },
  { "name": "Food", "ref": "categories/category4"}
];

let refs = ["categories/category2", "categories/category4"];

let newArr = [];

newArr = refs.map(value1 => categories.find(value2 => value2.ref === value1).name);

console.log(newArr); // Output: ["Computer", "Food"]

Answer №3

One efficient way to streamline your code is by utilizing the "find()" and "includes()" methods within the outer for loop:

let categories = [
  { "name": "Book", "ref": "categories/category1" },
  { "name": "Computer", "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++) {
  newArr.push(categories.find(v => v.ref.includes(refs[i])).name);
}

console.log(newArr); // ["Computer", "Food"]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is preventing JavaScript from parsing this specific string?

When I send a JSON encoded value from PHP to JavaScript and try to log it in the console, this is what I get: {"id":"4","username":"muzikant346","coins":"675","avatar1":"1","avatar2":"0","avatar3":"0","avatar4":"0","avatar_selected":"0"} The issue arises ...

Convert numerical values to currency format

Here is a number 5850 that I would like to format as currency. Format Example 1: 5850 => $58.50 Format Example 2: 9280 => $92.80 I am utilizing the function below: Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparat ...

What is the simplest method to import JSON within a node package?

If you're about to dive into my story below, I'm on the hunt for a more seamless method of loading JSON credentials within a module. My journey so far has been quite convoluted, and I suspect there must be a simpler way! My first attempt involve ...

Technique for wrapping and unwrapping a div during resizing?

I've been experimenting with using if else statements to achieve a simple task, but I'm struggling to reverse the wrapping of boxes after resizing the window above 650px. The goal is to have the boxes wrapped in a div when the window width is be ...

Navigate vertically using the pointer lock feature in THREE.js

I am seeking a way to achieve vertical movement using three.js's pointerlockcontrols. Specifically, I desire the movement to be similar to three.js's flycontrols, where the vertical direction of movement is proportional to the direction the user ...

Guide to Positioning Pre-Loader in the Center on Mobile Devices

Despite trying numerous solutions, I'm struggling to center my pre-loader on mobile devices. It looks fine on desktop and mobile landscape orientations, but whenever I switch to mobile portrait, it just won't center properly. CSS: .load ...

Tips for implementing a jQuery slider with dynamically generated IDs:

I've come up with automatically generated IDs like gallery-item-0, gallery-item-1, gallery-item-2 using PHP. How can I set up jQuery to initiate a slider for each ID? I wrote the following code, but it only works for the first ID. var i = 0; sle ...

Creating a custom Chrome extension with the ability to modify the pop-up window instead of the web page

Is there a way to modify the content inside my extension's pop-up without affecting the web page being viewed by the user? Also, how can I ensure that my dropdown list functions correctly? I have two dropdown lists where selecting an option from the ...

What is the best way to achieve a horizontally compact layout in Bootstrap by centering the content?

I am looking to center my content on the page and maintain a close proximity between items within a div. However, with Bootstrap 5, when I resize the page wider, additional space is added which pushes the items apart. Is there a way to keep them compacted ...

Assign a value to the Angular directive for the SharePoint People Picker

In my create form, I have successfully used a directive to capture and store values in SharePoint via REST. The directive I am using can be found at this link. Within my HTML, I am implementing the directive like this: <sp-people-picker name="CC" id=" ...

Ways to access a clicked element using AngularJS with ngClick

I am attempting to dynamically add a class to an element when it is clicked using AngularJS. The element is generated through ngRepeat, and I need to determine which specific element was clicked by utilizing the ng-click="foo()" directive. Here is a snipp ...

Converting integers to strings is not possible, just as converting strings to two-dimensional integer arrays is not

I find myself once again trying to solve the puzzle of error messages that keep appearing. Currently, I am delving into working with arrays - both regular and multi-dimensional. However, I am encountering difficulties in two areas: a) populating the arra ...

Troubleshooting issue with JavaScript sorting function failing to arrange elements in ascending

I'm having trouble sorting numbers in ascending order using JavaScript. Here's the code snippet: <h2>JavaScript Array Sort</h2> <p>Click the button to sort the array in ascending order.</p> <button onclick="myFunctio ...

Extend the duration by a month using jQuery

I am working with two date input fields and trying to increase the month of one field by one and set that value to the second field. I am using the DD/MM/YYYY date format for this task. var firstDate= new Date($(#firstDate).val()); firstDate.setMonth(firs ...

Tips for populating div elements using javascript/jquery

I have encountered an issue with displaying data from MYSQL using innerHTML. When I try to use +=, it concatenates all the values in the array instead of creating new elements in the div. How can I resolve this? jQuery(document).ready( function() { $(".dr ...

Effortless navigation fails to glide seamlessly

I have scoured through numerous resources on achieving smooth scrolling, but I am still unable to make it work. I am considering writing the code in a "js/script.js" file and then pasting the link to "script.js" at the bottom of the main page. Do I need to ...

Having trouble retrieving the necessary data to generate a menu, the getStaticProps function is coming back as undefined

I'm currently working with Next.js 13 & Strapi, and my goal is to create a Menu component utilizing the getStaticProps function. To achieve this, I've implemented a Layout component within the _app.js file, and nested a Menu component inside the ...

What is the best way to limit the values of an object within a JSON schema?

I am looking to restrict the types of values allowed for my object. Specifically, only string and array (of strings) are permitted: "myobject": { "string": "foo", "array": [ "bar", "baz", ], "bool": true, // invalid "object": {}, // inva ...

Determine if the data in an HTML table should be spanned when it

I'm facing a scenario where my HTML table contains duplicate data in a particular column, as illustrated below I am looking to automatically merge the cells of rows in the HTML table if the data in them is identical, similar to the table displayed be ...

jQuery is replacing spaces in the link with %2520 instead of %20

$(".row").each(function(){ $(this).attr('href', $(this).attr("href").replace(/\s/g,"%20")); }); Upon clicking the link, it seems to generate %2520 instead of %20. ...position=Administrative%2520Assistant-%2520Robotics Have you com ...