3

I have an array of empty objects like this:

var a = [ {}, {}, {}, {}, {}, {} ];

And an array of properties:

var colors = ["red", "green", "blue"];

I need to assign each color in "colors" to every element of "a" array with angular foreach. But the length of "a" array is greater than "colors". I want to assign the colors "by circle" So the result needs to be like this:

var a = [
    {color: "red"},
    {color: "green"},
    {color: "blue"},
    {color: "red"},
    {color: "green"},
    {color: "blue"},
    {color: "red"}
];

angular.forEach(a, function(elem, index) {
  if (a.length > colors.length) {
    // .......                       
  }
  elem.color = colors[index];
});

The question: Is there some way to reset the index of foreach to start looping the "colors" array from beginning? Thanks for help

2
  • 3
    Try this elem.color = colors[index % colors.length]; Commented May 8, 2017 at 6:22
  • @Hadi Thanks for help! Commented May 8, 2017 at 6:26

3 Answers 3

6

try this

var a = [ {}, {}, {}, {}, {}, {} ];
var colors = ["red", "green", "blue"];

a.forEach(function(item,key){
    item.color = colors[key % colors.length];
})
console.log(a)
Sign up to request clarification or add additional context in comments.

Comments

3

try javascript map function like this

var a = [ {}, {}, {}, {}, {}, {}, {} ]; 
var colors = ["red", "green", "blue"];

a = a.map(function(o,i){
    var color =  (colors[i]) ? colors[i] : callFunc(i);    
    o.color =color;
    
    return o;
    
    function callFunc(i){
       var diff = (i - colors.length)% (colors.length)
       return colors[diff]
    }
})

console.log(a)

Comments

0

You can simply have a counter i inside the foreach. In each iteration increment i like i++ and once it reaches the length of colors array, just reset it like i=0 and the color[i] can be used to get the color name.

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.