Extracting values from an array of objects using a second array in JavaScript

I need help filtering an array based on values from another array. The first array consists of objects with dropdown options, while the second array contains values that should match with the first array. How can I achieve this?

1st Array:

const books = [
    {
        label: "To Kill a Mockingbird",
        value: 1
    },
    {
        label: "1984",
        value: 2
    },
    {
        label: "The Lord of the Rings",
        value: 3
    },
    {
        label: "The Great Gatsby",
        value: 4
    }
]

Code Snippet provided:

const idString = "1,2,3";

function getSelectedOption(idString, books) {
        const ids = idString.split(",");
        const selectedOptions = [];

        ids.map(e => {
            const selected = books.map(options => {
                if (options.value === e){
                    return {
                        label: options.label,
                        value: options.value
                    }
                }
            })
            selectedOptions.push(selected)
        })

        return selectedOptions
    }

Result obtained:

[
    [undefined, undefined, undefined, undefined],
    [undefined, undefined, undefined, undefined],
    [undefined, undefined, undefined, undefined]
]

Expected Outcome:

[
    {
        label: "To Kill a Mockingbird",
        value: 1
    },
    {
        label: "1984",
        value: 2
    },
    {
        label: "The Lord of the Rings",
        value: 3
    }
]

Answer №1

To ensure that the values are unique, you can modify your code like this to retrieve them in order.

const idString = "1,2,3";

function getSelectedOption(idString, books) {
  const ids = idString.split(",");
  return ids.map(id => books.find(book => book.value == id)).filter(Boolean)
}

If you are not concerned about the order or if the value is not unique, you can filter the books array instead.

const idString = "1,2,3";

function getSelectedOption(idString, books) {
  const ids = idString.split(",");
  return books.filter(book => ids.includes(book.value.toString()))
}

Keep in mind that these algorithms have a time complexity of O(n*m) and may not be efficient with large datasets. However, they can still be used effectively if one of the arrays is relatively small.

Answer №2

let findSelectedOption = (idStr, library) => {
    let convertedArr = stringToArray(idStr)
    return library.filter(item => idStr.includes(item.value))
}

let stringToArray = (str) => {
    return str.split(",")
}

Answer №3

Utilizing the array method filter:

function retrieveSelectedOption(idValues, assortment) {
  const ids = idValues.split(",");
  return assortment.filter((item) => ids.includes(item.value.toString()));
}

const books = [{
    label: "To Kill a Mockingbird",
    value: 1
  },
  {
    label: "1984",
    value: 2
  },
  {
    label: "The Lord of the Rings",
    value: 3
  },
  {
    label: "The Great Gatsby",
    value: 4
  }
]

const idValues = "1,2,3";

retrieveSelectedOption(idValues, books);

console.log(retrieveSelectedOption(idValues, books));

Answer №4

Here are some improvements for your code

  • After splitting the idString, make sure to cast the values as numbers
  • Consider using find instead of map when looking for a specific value

const books = [
  {
    label: 'To Kill a Mockingbird',
    value: 1
  },
  {
    label: '1984',
    value: 2
  },
  {
    label: 'The Lord of the Rings',
    value: 3
  },
  {
    label: 'The Great Gatsby',
    value: 4
  }
]

const idString = '1,2,3'

function getSelectedOption(idString, books) {
  const ids = idString.split(',').map(Number)
  const selectedOptions = []

  ids.forEach(e => {
    const selected = books
      .map(options => {
        if (options.value === e) {
          return {
            label: options.label,
            value: options.value
          }
        }
      })
      .filter(options => options !== undefined)
    selectedOptions.push(selected[0])
  })

  return selectedOptions
}

console.log(getSelectedOption(idString, books))

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

Utilizing Python to store a collection of string values in an Excel spreadsheet

My data consists of individuals represented by arrays of strings: person1=["amy","fisher",34,"teacher"] person2=["john","wayne",45,"astronaut"] I am looking to organize this information into an Excel table with headers as follows: name family_name age ...

Techniques for iterating through an array within another array using AngularJS

I am working with a limited number of records and attempting to utilize a foreach loop in the controller. var values = [[{"code":"sd","description":"d"}],[{"code":"gh","description":"d"}]] angular.forEach(values, function(value, key){ console.log(key + & ...

Store the user input in an array and then display the highest value stored

I am developing a software that requires the user to enter 5 values ranging from 0 to 100 and then stores them in an array. The objective is to display the highest value entered by the user. The issue I'm encountering is that even after the input of t ...

What is the best way to calculate the average price?

Looking for help to calculate the average price of products with the available option "no" in a 2D array. Can anyone assist with this? public class Test { public static void main(String[] args) { double total = 0; Products[][] names = ...

Issue with getStaticProps not updating fetched values in Next.js production environment

I am currently working on building a blog using Next.js. Since the back-end is taken care of by another team, I am utilizing fetch API calls in getStaticProps to retrieve my articles, even though it may be considered best practice to interact with the data ...

Display multiple selection using JavaScript based on the element ID

I have a task to display the selected id using JavaScript, but currently, only the first select id is shown. Here is my HTML and JavaScript code: <tr> <td> <select name="jens_id[]" id="jens_id" required="" > <option ></op ...

I am interested in updating the content on the page seamlessly using Angular 6 without the need to reload

As a newcomer to Angular, I am interested in dynamically changing the page content or displaying a new component with fresh information. My website currently features cards, which you can view by following this Cards link. I would like to update the page ...

Tips for organizing an Enum and inserting it into an array

I am working with an enum and have defined its values: Customer("Customer"), BankName("Bank Name"), AccountNumber("Account Number"), Amount("Available Amount"); In addition, I have an array called realOrder which stores the indices in the ...

Inaccurate Feedback on Maquest Direction Route API

Currently, I am in the process of implementing the MapQuest API Direction Routing function on my website. However, upon submitting a request to the API, it is returning inaccurate routing points between two destinations. Here is the request form that I am ...

Using onDoubleClick with MUI TextField: A Quick Guide

Whenever the user double clicks the input field, I would like to automatically select the text. I have created a function for this specific action: export const selectText = ( event: React.MouseEvent<HTMLInputElement | HTMLTextAreaElement, MouseEvent& ...

Looking to automatically populate input fields using AJAX?

Need help auto filling input bars with AJAX, encountering a small issue Below is the HTML code: <input type="text" name="url" id="url"> <input type="text" name="name" id="name"> <input type="text" name="catagory" id="catagory> When t ...

Ways to showcase Material-UI Grid components without using cards

I initially used Material-UI grid items for spacing adjustments, but now they are displaying as cards. I would prefer them to be invisible like before, but the documentation doesn't provide a solution for this issue. Any assistance would be greatly ap ...

Implementing a feature in JavaScript to close one accordion when another is clicked on

I am seeking assistance in resolving the JavaScript code for my sidebar. While I've noticed that most people use jQuery for this task, I would prefer to stick with plain JavaScript as I am still new to it. If you are reading this, please refrain from ...

Retrieve an int array from the GetValue method

When I try to retrieve an int array using the method GetValue(this, null), I am only getting "System.Int32[]". Any suggestions on how to fix this? I am expecting the output to be the value of consequences2 (when the function is called with textNum = 2), ...

The checkbox within the modal popup is failing to trigger the mousedown event on the external popup button

In the world of Drupal, there exists a unique phenomenon known as the modal popup - essentially a dialog box that appears within an iframe. One user found themselves faced with the challenge of triggering a mousedown event on a submit button located outsid ...

Customizing holiday events with color after triggering an Ajax request in FullCalendar

I've been exploring the possibilities of enhancing my project with FullCalendar. My main goal is to set different background colors for holidays. After researching extensively, I've come across a potential solution using the dayRender hook. Howev ...

Do I need to implement server side rendering in Vue or React to secure my REST API?

When my REST API is located on the same machine as the SSR of Vue or React (NUXT, NEXT), is it still necessary to secure the API? ...

Instructions for creating a dropdown menu button that can also act as a link button

I'm struggling with my HTML code and can't seem to get the button to work as a link. Even after inserting an anchor tag with a link inside, clicking on the button does nothing. <!DOCTYPE html> <html lang="en"> <head> ...

$scope disappears following asynchronous call

In a previous project, I had this code working flawlessly. However, when I transferred the code to a new project, even the simplest case is failing. This is what my controller looks like: angular.module('myApp.controllers'). controller(' ...

What is the alternative to using toPromise() when utilizing await with an Observable?

This website mentions that "toPromise is now deprecated! (RxJS 5.5+)", however, I have been utilizing it recently with AngularFire2 (specifically when only one result is needed) in the following manner: const bar = await this.afs.doc(`documentPath`).value ...