skip to Main Content

I’m trying to do this coding challenge that takes a list and an index and returns the values in increments of the index. for example…

combo([1, 2, 3, 4], 2) ➞ [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

when I try to grab the values it also grabs the commas and messes up the code. It’s currently returning 1,23,4 and so on.

let newList = [];

function nCombo(list, index) {
  let newIndex = 0 + index;
  for (i = 0; list.length >= i; i += index) {
    newList.join(list.slice(i, newIndex));
    console.log(`slice = ${list.slice(i,newIndex)}`)
    console.log(newList);
    newIndex += index;
  }
  console.log(newList);
}

nCombo([1, 2, 3, 4, 5, 6], 2)

I tried to use join before I was using newList += list.slice(i , newIndex);

I don’t know why it’s doing this

2

Answers


  1. This was my attempt at the coding challenge you suggested. I’m not sure if my for loops provide the correct functionality, but .push() is working just fine.

    Hopefully this helps,

    function combo(arr, index) {
      const result = [];
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length; j++) {
          if (i > j || i - j > index) {
            result.push([arr[j], arr[i]]);
          }
        }
      }
      return result;
    }
    const index = 2;
    const arr = [1, 2, 3, 4];
    
    // Example usage:
    console.log(combo(arr, index));
    Login or Signup to reply.
  2. You could take a recursive approach.

    function nCombo(list, size) {
        if (!size) return [[]];
        const result = [];
        for (let i = 0; i < list.length - size + 1; i++) {
            result.push(...nCombo(list.slice(i + 1), size - 1).map(a => [list[i], ...a]));
        }
        return result;
    }
    
    nCombo([1, 2, 3, 4], 2).map(a => console.log(...a));
    console.log('----------')
    nCombo([1, 2, 3, 4], 3).map(a => console.log(...a));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search