-1

I have three sets of data

var item = ['item1', 'item2', 'item3', ...]
var price = ['price1', 'price2', 'price3', ...]
var date = ['date1', 'date2', 'date3', ...]

Is there any way that I can arrange this into a specific order like

[
    ['item1', 'price1', 'date1'],
    ['item2', 'price2', 'date2'],
    ['item3', 'price3', 'date3'],
    .....
]

Thanks in advance.

Prism
  • 53
  • 5
  • are all these 3 arrays the same length? – hgb123 Nov 03 '21 at 10:47
  • Yes they are @hgb123 – Prism Nov 03 '21 at 10:48
  • Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. Please first ***>>>[Search for related topics on SO](https://www.google.com/search?q=javascript+merge+arrays+site%3Astackoverflow.com)<<<*** and if you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Nov 03 '21 at 10:48
  • @Prism This can be achieved using a loop logic, Please post what you have attemptd till now, so that we can help you where you are facing difficulty. – Nitheesh Nov 03 '21 at 10:50
  • Does this answer your question? [Transposing a 2D-array in JavaScript](https://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript) – Yevhen Horbunkov Nov 03 '21 at 11:01

4 Answers4

4

You can try with for loop or map function

const item = ['item1', 'item2', 'item3'];
const price = ['price1', 'price2', 'price3'];
const date = ['date1', 'date2', 'date3'];

const result = item.map((v, i) => [v, price[i], date[i]]);
Pooya
  • 2,968
  • 2
  • 12
  • 18
2

Given that your arrays are all in the same length, below is a short way that you could achieve your expected result

var item = ['item1', 'item2', 'item3']
var price = ['price1', 'price2', 'price3']
var date = ['date1', 'date2', 'date3']

const res = Array.from({
  length: item.length
}, (_, i) => [item[i], price[i], date[i]])

console.log(res)
hgb123
  • 13,869
  • 3
  • 20
  • 38
2

I assume your data is sorted as intended, even the length of different array is not the same the code below should work

const arranged = []
const length  = Math.min(item.length, price.length, date.length)
for (let index = 0; index < length; ++index){
    arranged.push([item[index], price[index], date[index]])
}

console.log(arranged)
Hachour Fouad
  • 52
  • 1
  • 6
1

I suggest you do objects instead

var item = ['item1', 'item2', 'item3']
var price = ['price1', 'price2', 'price3']
var date = ['date1', 'date2', 'date3']

const res = item.reduce((acc,cur,i) => {
  acc[i] = {item:cur,price:price[i], date:date[i] }
  return acc
}, [])

console.log(res)
mplungjan
  • 169,008
  • 28
  • 173
  • 236