0

I want to know how to repeat an array with another array based on the first value. When create a new array how to add an index for each row. Example:

Table Base
Total | Item | Description   | Price
5     | 946  | T-Shirt Red   | $10
3     | 456  | T-Shirt Black | $12
2     | 489  | T-Shirt Blue  | $11.50

Table Result
Index | Total | Item | Description   | Price
1     | 5     | 946  | T-Shirt Red   | $10
2     | 5     | 946  | T-Shirt Red   | $10
3     | 5     | 946  | T-Shirt Red   | $10
4     | 5     | 946  | T-Shirt Red   | $10
5     | 5     | 946  | T-Shirt Red   | $10
1     | 3     | 456  | T-Shirt Black | $12
2     | 3     | 456  | T-Shirt Black | $12
3     | 3     | 456  | T-Shirt Black | $12
1     | 2     | 489  | T-Shirt Blue  | $11.50
2     | 2     | 489  | T-Shirt Blue  | $11.50

I made this code, but I don't know how to make it work.

var data = [[5,946,'T-Shirt Red',10],[3,456,'T-Shirt Black',12],[2,489,'T-Shirt Blue',11.50]];
var items = [];
var i, j;

for(i in data){
    for (j = 1; j <= data[i][0]; j++) {
    items.push([j,data[i]]);
  }
}

console.log(items);

0

1 Answer 1

1

In modern browsers, it's a simple change

items.push([j, ...data[i]]);

for supporting IE, you'd need to change that to

items.push([j].concat(data[i]));

var data = [[5,946,'T-Shirt Red',10],[3,456,'T-Shirt Black',12],[2,489,'T-Shirt Blue',11.50]];
var items = [];
var i, j;

for(i in data){
    for (j = 1; j <= data[i][0]; j++) {
    items.push([j,...data[i]]);
  }
}
items.forEach(item => console.log(item.join('\t| ')))

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

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.