G Josh
G Josh

Reputation: 311

How to get values in an array of objects using another array - Javascript

I have a function that interacts with 2 arrays, 1st array is an array of objects that contain my dropdown options, second array is an array of values. I'm trying to filter the 1st array to return what has matched the values in my 2nd array. How do 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 below:

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:

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

Expected Result:

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

Upvotes: 2

Views: 2965

Answers (4)

Antoine Eskaros
Antoine Eskaros

Reputation: 851

Assuming that value is unique, you can update your code as following to get 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)
}

You can also filter the books array if you don't care about the order or in case that the value is not unique.

const idString = "1,2,3";

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

Please note that these are O(n*m) algorithms and it should not be used with large sets of data, however if one of the arrays is relatively small you can use it.

Upvotes: 3

hgb123
hgb123

Reputation: 14891

Some fixes to your solution

  • After split idString, it would result in array of string value, so you have to cast it to number
  • Instead of use map to get selected, you should use find

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))

Upvotes: 0

Andrew Arthur
Andrew Arthur

Reputation: 1603

Using an array filter:

function getSelectedOption(idString, books) {
  const ids = idString.split(",");
  return books.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 idString = "1,2,3";

getSelectedOption(idString, books);

console.log(getSelectedOption(idString, books));

Upvotes: 0

Yasmin
Yasmin

Reputation: 343

function getSelectedOption(idString, books) {
    const idArray = convertStringToArray(idString)
    return books.filter(item => idString.includes(item.value))
}

function convertStringToArray(string) {
    return string.split(",")
}

Upvotes: 1

Related Questions