Skip to content Skip to sidebar Skip to footer

Javascript Program - Deleting An Element From An Array

The program I wrote is about how a sports equipment company monitor the trampoline use; it records the customer NAME, and their STATUS (child or adult) that are currently on the tr

Solution 1:

Solution

//maximum customer on the trampoline is 5constMAX_CUSTOMERS = 5;

//create new Arrayvar customerList = newArray();

//add customerfunctionaddCustomer() {

    //check max customersif (customerList.length >= MAX_CUSTOMERS) {
        alert('Sorry, no more than ' + String(MAX_CUSTOMERS) + ' customers are allowed on the trampoline.');
    } else {
        //add new uservar newIndex = customerList.length;
        customerList[newIndex] = newObject;

        //ask user enter their name
        customerList[newIndex].name = prompt('What is the customer\'s name?');

        //ask user enter their status   
        customerList[newIndex].status = prompt('Are you a Child or an Adult?');

        //check user is child or adultwhile (!(customerList[newIndex].status == 'child' || customerList[newIndex].status == 'adult')) {
            customerList[newIndex].status = (
            prompt('Error Please Enter \'child\' or \'adult\':'));
        }
    }
}

//display customersfunctiondisplayAllCustomers() {
    //create messagevar message = '';

    //loop customersfor (var i = 0; i < customerList.length; i++) {
        //add customer to message
        message += customerList[i].name + ', Status: ' + String(customerList[i].status) + '. \n';
    }

    //check messageif (message == '') {
        message = 'There are no customer to display!';
    }

    //output messagealert(message);
}

//delete last customerfunctiondeleteLastCustomer() {
    //check customer listif (customerList.length > 0) {
        //delete last customer
        customerList.length--;
        alert('The last customer has been deleted.');
    } else {
        alert('There are no customer to delete!');
    }
}

//identify then delete customerfunctionidentifyThenDeleteCustomer() {
    //get customer namevar customerName = prompt('Enter the name of the customer to delete:');

    //get customer statusvar customerStatus = prompt('Enter \'child\' or \'adult\':');

    //check customer statuswhile (!(customerStatus == 'child' || customerStatus == 'adult')) {
        customerStatus = prompt('Error - enter \'child\' or \'adult\':');
    }

    //delete customerdeleteCustomer(customerName, customerStatus);
}

//delete customerfunctiondeleteCustomer(aName, aStatus) {
    //create new arrayvar newCustomerList = newArray();

    //loop customersfor (var i = 0; i < customerList.length; i++) {
        var customer = customerList[i];

        //check customerif ((customer.name != aName) || (customer.status != aStatus)) {
            //add new uservar newIndex = newCustomerList.length;
            newCustomerList[newIndex] = customer;
        }
    }

    //check deletedif (newCustomerList.length < customerList.length) {
        alert('The customer has been deleted.');
    } else {
        alert('There are no customer to delete!');
    }

    //update customer list
    customerList = newCustomerList;
}

So above you can find the solution, as Brandon mentioned, a new array has been created, in which each customer was added if this customer was not the one you were looking for. Therefore leaving you with an array without the customer you were looking for, this new array then replaces your original one.

Solution 2:

You could return a new array.

var fruits = ['apple', 'banana', 'carrot'],     // This is an array of fruits.
    deleteFruit = function (name) {             // A name of a fruit is an argument.var i = 0,
            newFruits = [];

        fruits.forEach(function (fruit) {       // It cycles through the list of fruits.if (fruit !== name) {               // If the current fruit is not the argument,
                newFruits[i] = fruit;           // add the fruit to a new array of fruits.
                i++;
            }
        });

        return newFruits;                       // Return the new array of fruits.
    },
    printFruits = function () {
        fruits.forEach(function (fruit) {
            alert(fruit);
        });
    },
    exec = function () {
        fruits = deleteFruit('apple');          // Set the old array equal to the returned array.
    };

exec();
printFruits();

JSFiddle: http://jsfiddle.net/Lf2e85ed/3/

Edit: Added comments to clarify. Is that better? The idea is that you can recreate the functionality of a splice() method by creating a new array of fruits, adding all of the fruit which are not the deleted fruit, and returning that new array.

In this case, we deleteFruit('apple'). Therefore, we cycle through the list of fruits (apple, banana, carrot). For each fruit, if it is not an apple, we add it to the new array of fruits. That means our new array of fruits contains banana and carrot. The function returns the new array of fruits, and it's assigned to the old array of fruits.

If you start with three fruits, and then you end up with two fruits, you've deleted one. You don't have to use splice(). In fact, it wouldn't surprise me if functions like splice() perform their functionality in a way similar to this, though the people who invented splice() surely did a better job than I did.

I hope this helps.

P.S. A carrot is a fruit now. :)

Post a Comment for "Javascript Program - Deleting An Element From An Array"