Refactor JavaScript snippet for given problem statement.
var arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; var arr2 = [1, 2, 3, 4, 5, 6]; var arr3 = [11, 22, 5, 6]; var arr4 = ["tom","cat","bob"]; arr1.foreach{ // length = 7 //do something } arr2.foreach{ // length = 6 //do something } arr3.foreach{ // length = 4 //do something } arr4.foreach{ // length = 3 //do something }
Below code fulfill my objective but it's checking un-necessary condition for arr4 (7 times instead of 3),
arr3 (7 times instead of 4),
arr2 (7 times instead of 6)
because it's inside max length 7 iteration.
const zip = (...arr) => Array.from( { length: Math.max(...arr.map(a => a.length)) }, (_, i) => arr.map(a => a[i] || null ) ); var arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; var arr2 = [1, 2, 3, 4, 5, 6]; var arr3 = [11, 22, 5, 6]; var arr4 = ["tom","cat","bob"]; var a = zip(arr1,arr2,arr3,arr4); a.forEach(function(item, index, array) { //console.log(index, item); console.log("--------------------"); (item[0] === null) ? "nothing" : console.log("first array " + item[0]); (item[1] === null) ? "nothing" : console.log("second array " + item[1]); (item[2] === null) ? "nothing" : console.log("third array " + item[2]); (item[3] === null) ? "nothing" : console.log("third array " + item[3]); });
Top comments (1)
Hello ! Don't hesitate to put colors on your
codeblock
like this example for have to have a better understanding of your code 😎