I am playing with array and object. If index value is 2, index value will get two stars symbols, and so on. I would like to get this result.
**2
******6
****4
***3
let arr = [
{'item': 2},
{'item': 6},
{'item': 4},
{'item': 3},
]
for(let i = 0; i < arr.length; i ) {
let obj = arr[i]
for(let key in obj) {
let x = '*' obj[key]
console.log(x)
}
}
I am stuck here =>
*2
*6
*4
*6
*3
CodePudding user response:
Maybe you want to use let x = "*".repeat(obj[key]) obj[key]
This method returnes n times the string (let n be the argument). For example "*".repeat(5)
returns "*****".
CodePudding user response:
How about:
let arr = [
{'item': 2},
{'item': 6},
{'item': 4},
{'item': 3},
]
arr.forEach(item => {
console.log("*".repeat(item['item']) item['item'])
})
CodePudding user response:
Use object.values
in a for/or loop to get the values of each object in the array and string.repeat
to multiply your '*' by that value:
let arr = [
{'item': 2},
{'item': 6},
{'item': 4},
{'item': 3},
]
for(let i = 0; i < arr.length; i ) {
let obj = arr[i]
for (const value of Object.values(obj)) {
let x = '*'.repeat(value);
console.log(x value);
}
}
CodePudding user response:
padStart is another option. You don't need the obj
variable.
let arr = [
{ 'item': 2 },
{ 'item': 6 },
{ 'item': 4 },
{ 'item': 3 },
]
for (let key of arr) {
let x = ''.padStart(key.item, '*') key.item;
console.log(x)
}
CodePudding user response:
One way is to do with Array fill
and concat
methods.
const arr = [{ item: 2 }, { item: 6 }, { item: 4 }, { item: 3 }];
const stars = (n) => Array(n).fill("*").join("").concat(n);
arr.forEach(({ item }) => console.log(stars(item)));