0

I am trying to make this 2 different array

array1 = ["ramu", "raju", "ravi"] ;
array2 = [10, 20, 30];

want to be in single array name

arrayNeed =[{name:"ramu",amt:10},{name:"raju",amt:20},{name:"ravi",amt:30}];

2 Answers 2

2

You are looking to zip array1 and array2. You should use map for this:

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

array1 = ["ramu", "raju", "ravi"] ;
array2 = [10, 20, 30];    
arrayNeed = array1.map((x, i) => ({name: x, amt: array2[i]}))

source

Related to:

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

Comments

1

You can simply run forEach on the first array. This will accept a callback function with two args: item(one at a time), index of that item in the array.

Since you'll have the index, you can simply add a key named amt with a value of array2's value at index

Try this

array1 = ["ramu", "raju", "ravi"] ;
array2 = [10, 20, 30];
arrayNeed = [];

array1.forEach((item, index) => {
  arrayNeed.push({ name: item, amt: array2[index] });
})

A short-hand syntax could also be:

arrayNeed = array1.map((item, index) => ({ name: item, amt: array2[index] }))

or

arrayNeed = array2.map((item, index) => ({ amt: item, name: array1[index]  }))

2 Comments

@ionDev Since you are using Angular (and I guess typescript), you can use map instead of the old foreach. No need to push anything. See my answer.
I'm just trying to enhance my answer. Nothing wrong with that I guess. I'll also add any other way of doing this in the near future if I find one.

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.