Skip to content
Advertisement

return a new array containing the results of passing the original elements into the callbacks in an alternating fashion

what should I do to get [3, 1.5, 15, 3.5, 27, 5, 63] output? Should I change the second for loops location ? Thanks in advance.

let alternatingMap = function(array,callback1,callback2) {
    const newArr=[];
    for (let i = 0; i < array.length ; i += 2) {
        newNum1 = callback1(array[i]);
        newArr.push(newNum1)
    }
    for (let i = 1; i < array.length ; i += 2) {
        newNum2 = callback2(array[i]);
        newArr.push(newNum2);
    }
    return newArr;
};

let half = function(num) {
    return num / 2;
}

let triple = function(num) {
    return num*3
}


let numbers = [1,3,5,7,9,10,21] // My output [3, 15, 27, 63, 1.5, 3.5, 5]
console.log(alternatingMap(numbers,triple,half));

Advertisement

Answer

You could use only a loop with conditioned callback

let alternatingMap = function (array, callback1, callback2) {
  const newArr = []
  for (let i = 0; i < array.length; i += 1) {
    let newNum = (i % 2 === 0 ? callback1 : callback2)(array[i])
    newArr.push(newNum)
  }
  return newArr
}

let alternatingMap = function (array, callback1, callback2) {
  const newArr = []
  for (let i = 0; i < array.length; i += 1) {
    let newNum = (i % 2 === 0 ? callback1 : callback2)(array[i])
    newArr.push(newNum)
  }
  return newArr
}

let half = function (num) {
  return num / 2
}

let triple = function (num) {
  return num * 3
}

let numbers = [1, 3, 5, 7, 9, 10, 21]
console.log(alternatingMap(numbers, triple, half))

Moreover, you could still use two loops like your current way, a slight change is to mutate the new array

let alternatingMap = function (array, callback1, callback2) {
  const newArr = []
  for (let i = 0; i < array.length; i += 2) {
    newArr[i] = callback1(array[i])
  }
  for (let i = 1; i < array.length; i += 2) {
    newArr[i] = callback2(array[i])
  }
  return newArr
}

let alternatingMap = function (array, callback1, callback2) {
  const newArr = []
  for (let i = 0; i < array.length; i += 2) {
    newArr[i] = callback1(array[i])
  }
  for (let i = 1; i < array.length; i += 2) {
    newArr[i] = callback2(array[i])
  }
  return newArr
}

let half = function (num) {
  return num / 2
}

let triple = function (num) {
  return num * 3
}

let numbers = [1, 3, 5, 7, 9, 10, 21]
console.log(alternatingMap(numbers, triple, half))
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement