Home > Software engineering >  How do you extract a value from the array based on index of another array?
How do you extract a value from the array based on index of another array?

Time:04-21

How do i extract the label in the countryOptions array based on the index on the checkbox?

const checkbox = [1, 2]

export const countryOptions = [
    {
        label: 'Malaysia',
        index: 1,
    },
    {
        label: 'Singapore',
        index: 2,
    },
    {
        label: 'Brazil',
        index: 3,
    },
]

Example output:

const country = ['Malaysia', 'Singapore']

CodePudding user response:

  1. Define the countries array
  2. Iterate through checkbox array
  3. for each checkbox array item, find the matching index in the country array
  4. if a country is found, add its label to the countries array

Assuming that the country index is a number, and checkbox array always holds numbers.

let countries = [];

checkbox.forEach(countryIndex => {
  let country = countryOptions.find(country => country.index === 
  countryIndex);
  if (country) {
    countries.push(country.label);
  } else {
    //the country was not found, maybe an error you want to handle or notify the user.
  }
})

CodePudding user response:

This a classic use case for filter and map:

  1. filter the array by checking if the index is included in checkbox
  2. map the matching objects to their respective label

const checkbox = [1, 2];
const countryOptions = [{
    label: 'Malaysia',
    index: 1,
},{
    label: 'Singapore',
    index: 2,
},{
    label: 'Brazil',
    index: 3,
}];

let country = countryOptions
.filter(x => checkbox.includes(x.index))
.map(x => x.label);

console.log(country);

  • Related