2

I know that my question's title looks weird but I didn't know how to ask such a question.

I have two arrays

a = [1,2,3]

And

b = ["gf","gdf","gdf"]

I have a return statement like this:

return {
    options: a.map(value => ({ label: value, value: value }))
};

But I want the value inside options to take the values of the b array not of the a array. How to do this?

1
  • Perhaps you could indicate what the expected result is so it is clear what you are trying to do. Commented Mar 23, 2017 at 14:22

2 Answers 2

5

You can pass second parameter to map() which is index and use it to get elements from b array.

var a = [1,2,3], b = ["gf","gdf","gdf"]

var options = a.map(function(value, index) {
 return { label: value, value: b[index] }
})

console.log(options)

If you want to use ES6 and arrow functions you can get same result like this.

var a = [1,2,3], b = ["gf","gdf","gdf"]

var options = a.map((v, i) => ({label: v, value: b[i]}))
console.log(options)

Sign up to request clarification or add additional context in comments.

Comments

2

You can write a mapn function which iterates across multiple arrays, and calls a function whose arguments are taken from each of the arrays:

a = [1,2,3]
b = ["gf","gdf","gdf"]
    
function mapn(arrays, fn) {
  return arrays[0].map((_, i) => fn(...arrays.map(array => array[i])));
}

console.log(mapn([a, b], (label, value) => ({label, value})));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.