Greyson
Greyson

Reputation: 13

Recursively get every nth element from array Javascript

I have an array of colors that I need to recursively get every nth element to generate a legend. The colors array might look something like this:

[
'red',
'dark_red',
'dark_dark_red',
'green',
'dark_green',
'dark_dark_green',
'blue',
'dark_blue',
'dark_dark_blue'
]

I have a variable amount of legend items that I want to generate colors for. I want to be able to generate the colors based off of the index when looping through the legend items in a pattern like so:

1 - green
2 - blue
3 - dark_red
4 - dark_green
5 - dark_blue
6 - etc...

How might I go about this? I tried using modulus and a double-loop statement but was not able to generate the colors properly.

Upvotes: 0

Views: 563

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21658

StackSlave's answer is the most efficient way but if you want a recursive way you could do

const a = [
  'red',
  'dark_red',
  'dark_dark_red',
  'green',
  'dark_green',
  'dark_dark_green',
  'blue',
  'dark_blue',
  'dark_dark_blue'
];

const nthItems = (array, n) => {
  const results = [];
  const addItem = index => {
    if (index < array.length) {
      results.push(array[index]);
      addItem(index + n);
    }
  };
  addItem(0);
  return results;
};

console.log(nthItems(a, 2));
console.log(nthItems(a, 3));

But this is recursive purely for the sake of recursion, it adds values to the stack unnecessarily when a for loop will do.

Upvotes: 0

StackSlave
StackSlave

Reputation: 10617

To get the nthItems:

function nthItems(array, n){
  const r = [];
  for(let i=n-1,l=array.length; i<l; i+=n){
    r.push(array[i]);
  }
  return r;
}
const a = [
  'red',
  'dark_red',
  'dark_dark_red',
  'green',
  'dark_green',
  'dark_dark_green',
  'blue',
  'dark_blue',
  'dark_dark_blue'
];
console.log(nthItems(a, 2));
console.log(nthItems(a, 3));

Upvotes: 2

Related Questions