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}];
aloisdg
  • 22,270
  • 6
  • 85
  • 105
ionMobDev
  • 351
  • 1
  • 4
  • 20

2 Answers2

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:

aloisdg
  • 22,270
  • 6
  • 85
  • 105
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]  }))
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • @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. – aloisdg Oct 11 '18 at 12:50
  • 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. – SiddAjmera Oct 11 '18 at 12:54