Johnny Pachecp Asked: 2020-03-12 13:23:47 +0800 CST 2020-03-12 13:23:47 +0800 CST 2020-03-12 13:23:47 +0800 CST How to know when Map, Reduce, and Filter are done? [closed] 772 What is the best way to know when an array traversal ends in javascript with any of these functions? javascript 1 Answers Voted Best Answer Zoilo Reyes 2020-03-12T13:34:53+08:002020-03-12T13:34:53+08:00 For map and filter you can use the second parameter of the callback which indicates the index of the current element. For reduce use the third parameter of the callback. let arreglo = [1,2,3]; arreglo.map((elemento, indice) => { if(indice == arreglo.length - 1) console.log("Soy el último: " + elemento); return elemento; }) arreglo.filter((elemento, indice) => { if(indice == arreglo.length - 1) console.log("Soy el último: " + elemento); return true; }) arreglo.reduce((acumulador, valorActual, indice) => { if(indice == arreglo.length - 1) console.log("Soy el último: " + valorActual); return acumulador + valorActual; })
For map and filter you can use the second parameter of the callback which indicates the index of the current element.
For reduce use the third parameter of the callback.