Guide on filtering an array's keys using another array's numeric keys

I am working with two arrays. The structure of the first array is as follows:

items: [
    {
      name: "a",
      items: [
         { name: "jack" },
         { name: "jose" },
      ]
    },
    {
      name: "b",
      items: [
         { name: "lara" },
         { name: "jo" },
      ]
    },
    {
      name: "c",
      items: [
         { name: "andy" },
         { name: "hary" },
      ]
    }
]

Now, let's move on to the second array:

number: [
  0: [0, 1],
  1: [1],
  2: [0]
]

I need to filter the "items" based on the values in the "number" array. What would be the best solution to achieve the desired output?

{["jack", "jole"],["jo"],["andy"]}

Answer №1

To achieve the desired output, using a few maps would be helpful:

The requested result is not valid JavaScript, so I created a nested array

const arr1 = [{ name: "a", items: [{ name: "jack" }, { name: "jose" } ] }, { name: "b", items: [{ name: "lara" }, { name: "jo" }] }, { name: "c", items: [{ name: "andy" }, { name: "hary" }] } ], numbers = [ [0, 1], [1], [0] ]; 

const res = numbers
  .map((arr, i) => arr
    .map(key => arr1[i].items[key].name)
  )
console.log(res)

Answer №2

When your variable must be an Object in the number type.

let elements = [
  {
    label: "red",
    values: [{ id: 1 }, { id: 2 }]
  },
  {
    label: "blue",
    values: [{ id: 3 }, { id: 4 }]
  },
  {
    label: "green",
    values: [{ id: 5 }, { id: 6 }]
  }
];

let numberObj = {
  0: [0, 1],
  1: [1],
  2: [0]
};

let finalResult = []
for (const [index, array] of Object.entries(numberObj)){
  let labels = []
  array.forEach(item => {
    labels.push(elements[index].values[item].id)
  })
  finalResult.push(labels)
}

console.log(finalResult)

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

Discover the steps to integrating jsfiddle into my local development environment

If you want to check out the code for this example, head over to jsfiddle at this link. And below is a snippet of the HTML file: <!DOCTYPE html> <html> <head> <script src="http://www.jacklmoore.com/colorbox/jquery.colorbox.js" type= ...

How to perfectly align images in nivo slider

Currently, I am utilizing the nivo Slider within a div that has been styled with a width of 100%. Despite the slider functioning splendidly, I am encountering an issue where the images do not properly align in the center due to the javascript script consi ...

Ways to efficiently move through a JSON object

I need assistance with navigating through a JSON object to extract one element at a time and loop through it. See the JSON data below. { "noun": { "syn": [ "leap", "saltation", "startle", "start", "parachuting", " ...

Updating various elements of an object within an array using a patch operation

Currently delving into the world of web development. Here I am, working on my first express server and facing a little challenge: I am trying to update multiple values of an object within an array using app.patch, but struggling with the syntax. While my ...

PHP array_key_exists - flexible on certain data types, stringent on others

Despite my decent knowledge of PHP quirks, I found myself puzzled by the unexpected behavior demonstrated in the code below today: // loose $a = array(true => 'foo'); var_dump(array_key_exists(1, $a)); // strict $a = array('7.1' =& ...

What are the benefits of using Array.prototype.forEach.call(array, cb) instead of array.forEach(cb)?

After revisiting some snapshots from the recent ng-europe conference, I stumbled upon a slide that appears to showcase snippets of code from Angular 2. You can view it here: (Source: ) One thing that confuses me is this: What could be the reason behind t ...

What is the best way to censor words in an HTML form?

I have been contemplating ways to prevent certain words from being submitted in my form, specifically targeting the username field. My access to PHP/JS files is limited, so I am unsure about the necessary steps for implementation. <div class="form-grou ...

Guide on dividing objects according to an element from a nested object within an ArrayList using Java

Here is an example of a list of objects with one object in an array. I want to split the users list into different objects while maintaining the original object structure using Java. The data obtained from the database is shown below, along with the expect ...

Utilizing React for Conditional Rendering and Navigation Bar Implementation

When developing my applications in react-native, I am using the state and a switch statement in the main render function to determine which component should be displayed on the screen. While this is a react structure question, it has implications for my sp ...

What is the best way to remove an element from a specific position in an array?

Recently, I encountered a programming challenge where I needed to add the first two elements of an array and then place their sum at the first position (while removing the two nodes that were added). This process inevitably shifts the rest of the array for ...

Is it possible to obtain a single symbol from the string upon clicking?

I am working with a DOM document that contains text content like this: <p>Content scripts aren't completely cut off from their parent extensions. A content script can exchange messages with its parent extension</p> When I click on this H ...

Clickable Element Embedded within Event Date - Developed with Vue.js

Currently, I am utilizing Vuetify's calendar component. My task involves displaying and concealing specific information within a calendar event upon clicking a button located inside the same event. While I have succeeded in showing or hiding the div e ...

What is the reason behind the optional assignment of "window.$ =" in Vue.js imports, but mandatory for jQuery in JavaScript files?

There is an interesting behavior I've observed when using the "require" function with Vue versus jQuery. With Vue, I have found that the following statement structures work seamlessly in my application: window.Vue = require('vue'); window.$ ...

Ajax dependent dropdown is failing to load properly on the live server

My dropdown menus for country, state, and city are chained to each other, where the state options depend on the selected country and the city options depend on the selected state. While this functionality works perfectly on my local server, it's not w ...

Utilizing Vue.js to convert blobs into objects or strings and assign them to application variables

I am currently working on a Vue app and have the following setup: data: function() { return { modules: [], ... Along with the following method: methods: { submitted: function(){ ... axios({method: 'get', ...

JavaScript: The hyperlink provided in the data-href attribute is not functioning properly within the carousel

I have a carousel with images that I want to link to specific pages: JS Fiddle. My goal is to have each image in the carousel direct users to a different webpage when clicked. For example: Clicking on the wagon image should go to wagon.com Clicking on th ...

Struggling with grasping the concept of Filtering Array in Eloquent Javascript Chapter 5?

Currently diving into the world of JavaScript through the enlightening pages of Eloquent JavaScript. Chapter 5 has been a breeze so far, except for one line of code inside a console.log statement that has me stumped: function filter(array, test) { ...

Exploring the Fusion of Data in VueJS

Trying to figure out how to merge data from two different sources to display in a single table. One source is created within my Vue instance, while the other is imported from an API. Any suggestions on how to achieve this? HTML: <div class="ui conta ...

How can I pre-fill an AutoModelSelect2Field with static information in Django using the django-select2 library?

I am currently using a field similar to the one below: class ContactSelect(AutoModelSelect2Field): queryset = Contact.objects.all() search_fields = ['name__contains'] to_field = 'name' widget = AutoHeavySelect2Widget W ...

Tips for displaying the preceding div of a clicked div using Angular.js

I have an HTML structure that looks like this: <div class="main" ng-controller="firstcontroller"> <div class="submain"> <div class="first" ng-show="display">displayed</div> <div class="second" my- ...