I am using javascript and trying to duplicate an array item based off of the number of matches that are inside each item. I believe I need to use arr.map() to accomplish this but am having trouble with the evaluation logic.
So in the example below Item 1 would be duplicated 3 times and Item 2 would be duplicated 1 time. Thanks your help and your time.
My current array looks like:
"cards" = [
{
"text": "Item 1"
"matches": 3
}
{
"text": "Item 2"
"matches": 1
}
]
New Array would look like:
"newCards" = [
{
"text": "Item 1"
"matches": 3
}
{
"text": "Item 1"
"matches": 3
},
{
"text": "Item 1"
"matches": 3
},
{
"text": "Item 2"
"matches": 1
},
{
"text": "Item 2"
"matches": 1
}
]
attempting to use map function
let cardCounter = 0
let cardMap = cards.map(function (item){
cardCounter++
if (cardCounter < item.matches) {
// Not really sure what to return here....
// tried to return
// return[item, item]
// this returns an array where the first two keys are arrays and the rest undefined.
}
})
mapis the right tool for the job, unless you intend to return arrays and then flatten the result..forEach()or.reduce()would be more appropriate than.map()