简体   繁体   中英

How can i loop through 2 arrays at once and assign colours from array to each value of the other array

I have 2 arrays. one is an array of colours and the other is an array of objects (items).

I want to assign a colour from the first array to each of the objects in the second array.

array one:

var colours = ["#5cbae6", "#b6d957", "#fac364"];

Second array:

var items = [ itemOne, itemTwo, itemThree, itemFour, itemFive , itemSix.. ];

The items depend on the user. the user can provide one item or 30 items. So in some cases the colours will be less than items and in some cases they will be more.

What i want is to loop through "items" array and for each item to assign a colour from the array "colours"

example:

item one = 5cbae6
item two = b6d957
item three = fac364
item four = 5cbae6

once the last colour is assigned we should go back to the first colour and assign until all "items" have one colour.

pseudo code:

for each object in items loop through array colours and assign one colour to an item. when the third colour is reached start over from the first colour. each item has a property "setColor" and needs the value from "colours"

thanks in advance.

Use a forEach to loop through the items array. forEach provides the index of the current item item , use that index with % ( modulo operator) to get the index of the equivalent color:

items.forEach(function(item, index) {
    item.setColor( colours[ index % colours.length ] );
});

Explanation of modulo operator:

Let items.length be 10 and colours.length be 3 :

index === 0   =>   index % colours.length === 0 % 3 === 0   =>   first colour
index === 1   =>   index % colours.length === 1 % 3 === 1   =>   second colour
index === 2   =>   index % colours.length === 2 % 3 === 2   =>   third colour
index === 3   =>   index % colours.length === 3 % 3 === 0   =>   first colour
index === 4   =>   index % colours.length === 4 % 3 === 1   =>   second colour
index === 5   =>   index % colours.length === 5 % 3 === 2   =>   third colour
index === 6   =>   index % colours.length === 6 % 3 === 0   =>   first colour
index === 7   =>   index % colours.length === 7 % 3 === 1   =>   second colour
index === 8   =>   index % colours.length === 8 % 3 === 2   =>   third colour
index === 9   =>   index % colours.length === 9 % 3 === 0   =>   first colour

m % n < n where both m and n are integers and n != 0 .

Try this:

var ans = new Array();
for(var i = 0;i<items.length;++i){
    ans[items[i]] = colors[i%colors.length];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM