1

I have an array which is built from data dynamically, so it can change.

It's basically this:

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

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

For example, if the array is:

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

then it creates an array of:

[1, 1, 1, 1]

If the array is:

["bird", "fish"]

then it creates an array of:

[1, 1]

How can I do this?

3 Answers 3

2

You can use the Array.prototype.map method:

var input = ["foo", "bar", "baz"];
var mapped = input.map(function () { return 1; });
Sign up to request clarification or add additional context in comments.

2 Comments

There's an extra } on the right. Apart from that I tried console.log(mapped); but got nothing
Why does it say Undefined?
0

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

0
// es6
var array = ["t1", "something", "bird", "dog", "cow", "fish"]
array.map(() =>  1); // => [1, 1, 1, 1, 1, 1]

// if you don't care if they are strings 
'1'.repeat(array.length).split(''); //=> ["1", "1", "1", "1", "1", "1"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.