I need to push 0 in users element if the array's length is less than 7.
Example: If array has 2 elements. The rest should have 0 in it's users and _id as the index number.
Please help me to acheive this
const newUsers = [
{
_id: 1,
users: 8
},
{
_id: 2,
users: 6
},
{
_id: 3,
users: 1
},
{
_id: 4,
users: 8
},
{
_id: 5,
users: 0
},
{
_id: 7,
users: 0
}
]
Federico klez Culloca
27.3k17 gold badges61 silver badges102 bronze badges
-
Does this answer your question? replacing empty with zero values in arrayOnyx– Onyx2022年02月09日 20:23:25 +00:00Commented Feb 9, 2022 at 20:23
-
1What does the question have to do with the title?evolutionxbox– evolutionxbox2022年02月09日 20:25:00 +00:00Commented Feb 9, 2022 at 20:25
-
I mentioned it as a help. I tried my best and asked for a suggestion. Didn't asked for your "code-writing service" anyway.Ryuzaki– Ryuzaki2022年02月09日 20:25:13 +00:00Commented Feb 9, 2022 at 20:25
-
Can you please share to us the code? We can't write your code out from scratch. It is expected that you have at least written a bit of code before noticing a problem, and can't find any answers. For more information, please see Stack Overflow's guide on How to Ask.Viradex– Viradex2022年02月09日 20:36:33 +00:00Commented Feb 9, 2022 at 20:36
2 Answers 2
for (let i = newUsers.length; i < 7; i += 1) {
newUsers.push({ _id: i + 1, users: 0 });
}
answered Feb 9, 2022 at 20:24
Jean-Baptiste Martin
1,4591 gold badge11 silver badges21 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
According to this W3Schools article, you can use map operator to change all the users property.
const newUsers = [
{
_id: 1,
users: 8
},
{
_id: 2,
users: 6
},
{
_id: 3,
users: 1
},
{
_id: 4,
users: 8
},
{
_id: 5,
users: 8
}
]
if (newUsers.length < 7)
newUsers.map(x => x.users = 0);
console.log(newUsers)
answered Feb 9, 2022 at 20:37
FelipeHSouza
3831 gold badge3 silver badges10 bronze badges
Comments
lang-js