Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript : Iterate pushed elements in a same loop

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 ?

like image 587
Jaydeep Mor Avatar asked Apr 26 '26 02:04

Jaydeep Mor


2 Answers

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))
like image 192
Sourabh Somani Avatar answered Apr 28 '26 15:04

Sourabh Somani


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)
like image 36
Charlie Avatar answered Apr 28 '26 15:04

Charlie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!