+ 1
Converting objects into arrays
I have an object for example Const learn = { book: 3, Pen :2, Pencil :1 } How do I convert it to look like this [book, book, book, pen, pen, pencil ] It should vary on the value of each item in d object
6 Answers
+ 10
const learn = {
Book: 3,
Pen :2,
Pencil :1
}
const foo = Object.keys(learn).reduce((acc, curr) => {
return [
...acc,
...[...new Array(learn[curr])].map(_ => curr)
]
}, []);
+ 7
I'll break it down:
new Array(learn[curr]) => create new array of specified length, in our case the value of learn[curr].
putting the array in [...new Array(learn[curr])] will spread the arrays.
Without this step we would get an array of arrays => for learn[curr] = 3:
[[null, null, null]]
With the spread operator:
[null, null, null]
The next step is to map the array to the value of curr and again, the outer spread operator (...) is used again to flatten the result and merge with the accumulator (acc)
+ 1
const learn ={
book: 3,
Pen :2,
Pencil :1
}
arr=[];
for(let [i,j] of Object.entries(learn)){
for(let k=0;k<j;k++){
arr.push(i);
}
}
console.log(arr);
+ 1
for(let I in learn) {
var key=I;
let no=learn[key];
for(let x=0;x<no;++x) {
console.log(key);
}
}
Try this u can also store the output for proper output
0
Burey pls can you explain '[... new Array(learn[curr])] don't understand how it works
0
Burey thanks