Home > Software engineering >  How to arrange/edit multiple arrays | Javascript
How to arrange/edit multiple arrays | Javascript

Time:11-03

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.

CodePudding user response:

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]]);

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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)

CodePudding user response:

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)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related