Home > OS >  Drop it exercise using map()
Drop it exercise using map()

Time:03-23

I am answering this exercise in FreeCodeCamp here's the instruction Drop it Given the array arr, iterate through and remove each element starting from the first element (the 0 index) until the function func returns true when the iterated element is passed through it.

Then return the rest of the array once the condition is satisfied, otherwise, arr should be returned as an empty array.

this is what I have so far. I used the map function to iterate the indexes of array then check if it met the condition of the function parameter inside the map. In this case, the function should return only the numbers less than 3 but I can't get rid of 3 when returning it.


function dropElements(arr, func) {
return arr.map(x => func(x) ? x : "");
}
console.log(dropElements([1, 2, 3], function(n) {return n < 3; }));

CodePudding user response:

You could take a closure over a boolean value and keep a true value for the rest of the array for filtering.

Source of data/results: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it

function dropElements(arr, func) {
  return arr.filter((b => v => b ||= func(v))(false));
}

console.log(...dropElements([1, 2, 3], function(n) { return n < 3; }));       // [1, 2, 3]
console.log(...dropElements([1, 2, 3, 4], function(n) { return n >= 3; }));   // [3, 4]
console.log(...dropElements([0, 1, 0, 1], function(n) { return n === 1; }));  // [1, 0, 1]
console.log(...dropElements([1, 2, 3], function(n) { return n > 0; }));       // [1, 2, 3]
console.log(...dropElements([1, 2, 3, 4], function(n) { return n > 5; }));    // []
console.log(...dropElements([1, 2, 3, 7, 4], function(n) { return n > 3; })); // [7, 4]
console.log(...dropElements([1, 2, 3, 9, 2], function(n) { return n > 2; })); // [3, 9, 2]

CodePudding user response:

Would suggest using a filter, which returns another array:

function dropElements(arr) {
  return arr.filter(x => x < 3);
}

const someArray = [1, 2, 3];
console.log(dropElements(someArray)); // [1, 2]

CodePudding user response:

It says "remove elements" so I'm gonna mutate the array that was passed in.

function dropElements(arr, func) {
  while (arr.length && !func(arr[0])) {
    arr.splice(0, 1);
  }
  return arr;
}

console.log(dropElements([1, 2, 3], function(n) {return n < 3; }));

  • Related