Markcce Eros Markcce Eros - 1 month ago 12
Javascript Question

Javascript create array with fixed value but matching column amount from another array

Javascript create array with fixed value but matching column amount from another array

I have an array which is build from data it grads dynamically so it can change:

It's basically this:

["t1", "something", "bird", "dog", "cow", "fish"]


What I need to do it to count how many of them there are and create another array with the same amound of columns but all with the value of 1.

For example, if the array is:

[bird", "dog", "cow", "fish"]


then is creates an array of:

[1, 1, 1, 1]


If the array is:

[bird", "fish"]


then is creates an array of:

[1, 1]


How can i do this?

Answer

Just create a new array of equal length and use the fill function.

var myArray = ["dog","cat","monkey"];

var secondArray = new Array(myArray.length).fill(1);
Comments