How to iterate pushed value as well in a same loop.
I have one array like,
var arrays = [
"hii",
"hello"
];
I iterate using for in with push,
for (var index in arrays) {
arrays.push(arrays[index] + " world");
console.log(arrays[index]);
}
console.log(arrays);
Output :
hii
hello
Array(4): 0 : "hii", 1 : "hello", 2 : "hii world", 3 : "hello world"
jsFiddle.
Question : How do I iterate pushed element and iterate within same loop ?
You can do like as follows
[...arrays,...arrays.map(a=>a+' world')]
Example is as follows
var arrays = [
"hii",
"hello"
];
function appendWorld(arr){
return [...arrays,...arrays.map(a=>a+' world')]
}
console.log(appendWorld(arrays))
Edit: OP edited the question to include pushed elements too in the iteration
If you want to include the pushed elements during the iteration (which you claim to do conditionally to prevent infinity), you can use for loop with Array.length.
for (var i = 0; i < arrays.length; i++) {
if (some_condition)
arrays.push(arrays[i] + 'world');
}
The loop will always try to go up to the new length.
Previous answer:
The Array.forEach method doesn't apply the iterator to the elements those are pushed during the iteration.
const arrays = [
"hii",
"hello"
];
arrays.forEach((e, i, a) => {
a.push(e + ' world')
});
console.log(arrays)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With