JavaScript - Remove array element



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.



Solution 1 using shift


function dropElements(arr, func) {
    while (!func(arr[0])) {
        return arr.shift()
    }
    return result;
}
console.log(dropElements([1, 2, 3], function (n) { return n < 3; }));

Output:


[ 1, 2, 3 ]

Solution 2 Basic approach


function dropElements(arr, func) {
    let result = []
    for (let i = 0; i < arr.length; i++) {
        if (func(arr[i])) {
            return arr.slice(i);
        }
    }
    return result;
}

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

Output:


[ 3, 4 ]

Solution not working or have any suggestions? Please send an email to [email protected]



Join Our Facebook Group


Share this example


Download Android App

download android app

Popular javascript Examples









codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube