0

How to generate an array with function like this?

var name = ["monkey","monkey"..."horse","horse",..."dog","dog",..."cat","cat"...]​

In my real case, I may have to repeat each name 100 times..

2
  • You want to generate that based on array where every word occurs once? Commented Dec 10, 2015 at 19:23
  • for(var i = 0; i < 100; i++){ name.push('cat'); } Commented Dec 10, 2015 at 19:23

3 Answers 3

2

Assuming that you already have that words in a array try this code:

var words = ["monkey", "hourse", "dog", "cat"];
var repeatWords = [];
for(var i = 0; i < words.length; i++)
{
    for(var j = 0; j < 100; j++)
  {
    repeatWords.push(words[i]);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can try this, specifying the words to be used, and the times to create the array you need.

var neededWords = ["Cat", "Hourse", "Dog"];
    var finalArray = [];
    var times = 10;
    for (var i = 0; i < neededWords.length; i++) {
        for (var n = 0; n < times; n++) {
            finalArray.push(neededWords[i]);
            }
    }
    console.log(finalArray);

Hope that helps!

Comments

0

If I understood correctly you need a function that takes as an argument a collection of items and returns a collection of those items repeated. From your problem statement, I assumed that the repetition has to be adjusted by you per collection item - correct me if I am wrong.

The function I wrote does just that; it takes an object literal {name1:frequency1,name2:frequency2..} which then iterates over the keys and pushes each one as many times as indicated by the associated frequency in the frequencyMap object.

function getRepeatedNames( frequencyMap ) {
  var namesCollection = [];
  Object.keys(frequencyMap).forEach(function(name,i,names){
    var freq = frequencyMap[name];
    freq = (isFinite(freq)) ? Math.abs(Math.floor(freq)) : 1;
    for (var nameCounter=0; nameCounter<freq; nameCounter++) {
      namesCollection.push(name); 
    }
  });
  return namesCollection;
}

Non-numeric values in the frequency map are ignored and replaced with 1.

Usage example: If we want to create an array with 5 cats and 3 dogs we need to invoke

getRepeatedNames({cat: 2, dog: 3}); // ["cat","cat","dog","dog","dog"]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.