How to use a for loop and splice to remove a word and then check an array for a specific word

Tags: , , , ,



I want to make a function that looks for a specific name (Inger) in an array, and the removes that name. Then I want the function to tell that a name doesn’t exist in the array.

    var femaleName = ["Anne","Inger","Kari","Marit","Ingrid"]

    function removeElement (aTable, aName) {

        for (var i = 0; i <= aTable.length - 1; i++) {
            if (aTable[1] === aName) {

                aTable.splice(i, 1)
                document.write(aTable); {break;}

            } else if (aTable[i] !== aName) {
                document.write(aName + " is not in the list");
            }
        }
    }

I’ve tried to solve it this way, but I don’t get it right. The output should be something like this:

Anne, Kari, Marit, Ingrid
Victoria is not in the list

Answer

Do you have to write functions? Javascript has Array methods to do this for you.

Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

includes()

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

var femaleName = ["Anne", "Inger", "Kari", "Marit", "Ingrid"]

femaleName = femaleName.filter(name => name !== 'Inger')

console.log(femaleName);

console.log(femaleName.includes('Inger'));


Source: stackoverflow