How to remove an element from an object in JavaScript?

In Javascript, we can store and remove object data from an array in a variety of ways. The JavaScript array includes a number of techniques to clear up array data.

When removing elements from an array, you can use pop, shift, or splice to remove them from the middle, the beginning, or the end, respectively. A more advanced way to eliminate undesirable elements is to construct a new array using the JavaScript Array filter method.

Let us now look at those different methods to understand how to remove an object from an array in javascript.

Remove Object From an Array in JavaScript

In this section, we will learn how to remove objects from an array in javascript. So, let us look into each of the ways.

array.pop() Function in JavaScript

In JavaScript, the array pop() method deals with removing the last element of the array, in other words, the array.pop() method removes the last object of the array in JavaScript. After removing the element the array.pop() function also returns the element and updates the length of the array.

Syntax:

Parameters: The array.pop() method does not take any parameters.

Return Value: The array.pop() method pops and returns the last element (object) from the array in javascript.

Code:


// javascript program to demonstrate 
// array.pop() function in JavaScript

// array of objects
const dummy = [
  {item: 'pen', price: 10 },
  {item: 'pencil', price: 5 },
  {item: 'eraser', price: 5 },
  {item: 'copy', price: 20 },
];

// the popped object
popped_object = dummy.pop();

// printing the final results

// the original array
console.log("The original array = ",dummy);

// the popped object from the array
console.log("The popped object from the array = ",popped_object);

Output:

"The original array = " Array [Object { item: "pen", price: 10 }, Object { item: "pencil", price: 5 }, Object { item: "eraser", price: 5 }]
"The popped object from the array = " Object { item: "copy", price: 20 }

Explanation: In the above code, we have utilised the array.pop() method to delete the element from the array. The pop() method always removes the last item before returning it. Finally, we printed the array variable as well as the popped_object variable.

array.splice() Function in JavaScript

JavaScript's splice() method of the Array class alters the original array's contents. It functions by getting rid of the current elements and replacing them with new ones, which may affect the length of the array. Let us look into its syntax and examples for better understanding.

Syntax:

Below given is the syntax for the array.splice() method --

arr.splice(startIndex, deleteCount, element1, element2, ..., elementN)

Another syntax:

// only mentioning the startindex
splice(startIndex)

// mentioning both the startindex and deletecount
splice(startIndex, deleteCount)

Parameters: The splice() method accepts three parameters:

1. start_index (required): Represents the index from where the modification should begin. It is a mandatory parameter. If the starting index specified is positive then it begins from the 0th index of the array. In case the specified start index is negative, its counting will begin from the end index of the array, starting with -1.

How to remove an element from an object in JavaScript?

2. delete_count (optional): It represents the number of elements that should be deleted from the array. It is an optional parameter. The deletion starts from the starting index and goes till the number of the elements specified in the deleteCount. The delete count parameter should be set to 0 if it is not needed, otherwise, all the elements from the array will be removed from the starting index till the end.

How to remove an element from an object in JavaScript?

3. element1, element2,..., elementN (optional): They are the elements that would be added after the start index position(specified by us). They can accept elements of different data types. If not specified then only the existing element will be deleted and no new element will be added.

How to remove an element from an object in JavaScript?

Return Value: The array.splice() method in JavaScript returns the array which contains all the elements that have been removed from the actual or original array. If none of the elements is removed then it returns an empty array.

Code:


// javascript program to demonstrate 
// array.splice() function in JavaScript

// array of numbers
let num = [0, 1, 2, 3, 4, 5, 6];

//Array before any changes
console.log("Original array:", num);

// Removing one element at index 2 and adding the numbers 7, 8, and 9 in the array
let removedElements = num.splice(2, 1, 7, 8, 9);
//deletedElements will be an array 
// containing the elements removed from the array 'num'

//Printing the modified array 'num'
console.log("Our Array after removing elements:", num);

//Printing the array of removed Elements
console.log("Our removed element: ",removedElements);

Output:

> "Original array:" Array [0, 1, 2, 3, 4, 5, 6]
> "Our Array after removing elements:" Array [0, 1, 7, 8, 9, 3, 4, 5, 6]
> "Our removed element: " Array [2]

Explanation: In the above example, we removed element 2 from our original array. Since only 1 element was to be removed we specified delete_count as 1. Also, we added 3 new elements to the array (7, 8 and 9). Finally, we printed our array after the deletion and addition of the elements and the removed element.

array.shift() function in JavaScript

Javascript's built-in shift method for arrays removes the array's first element and returns the deleted element. The initial array's length is changed via this function. Let us look into its syntax and examples.

Syntax:

Below given is the syntax for the array.shift() in javascript.

Here, the word array refers to the name of a variable that holds an array of elements. To remove an element from a variable, add the function shift() and a dot to the end of the variable.

Parameters: You don't need to specify parameters when using shift() because this function doesn't take any.

Return Value: There are 2 instances of return values. It occasionally returns elements or is undefined.

  • The first element is deleted and the removed element is returned if the array is not empty.
  • The undefined value is returned if the array is empty.

Code:

// javascript program to demonstrate 
// array.shift() function in JavaScript

//implementation of javascript shift function
var stationary = ["books", "pens", "copy", "marker"];
var shifted_elements = stationary.shift();


// printing the stationary array after 
// Javascript Shift method is used
console.log("After shifting the element from the array", stationary);

//Element that is shifted
console.log("The shifted element: ",shifted_elements);

Output:

> "After shifting the element from the array" Array ["pens", "copy", "marker"]
> "The shifted element: " "books"

Explanation: In the above example, we are removing the first element from the stationary array and assigning the removed element to the shifted_elements variable that contains the return value Finally, we have printed the resultant array and the returned value.

array.slice() function in JavaScript

Javascript's slice() function creates a new array object from a shallow copy of a subarray that contains the elements from a user-specified start index to a user-specified end index (end not included). The initial array is left unchanged. Let us look into its syntax and examples.

Syntax: For the function slice in javascript, there are several different syntaxes, let us cover them:

// Different syntaxes for array.slice() 
// depending upon the parameters passed

// with 0 parameter
ar.slice()

// with 1 parameter
ar.slice(start)

// with 2 parameters
arr.slice(start, end)

Parameters:

Let us look into the parameters of the shift method in javascript. 1. Start: It is an optional parameter and its default value is 0. It represents the starting index from where the new array object will be created. Please note that it is inclusive and will be included in the new array.

2. End: It is an optional parameter as well, and its default value is the length of the array. It represents the end up to which the elements of the array will be included. Please note that it is exclusive in nature, so the element before this index will be the last element in the new array.

Return Value: Every time the Javascript function's array slice is used, a new array object containing the elements from the specified start index to the specified end index is returned (not including the end index).

The original array's values will all be included in the new array if neither of these values is supplied.

Code:

// javascript program to demonstrate 
// array.slice() function in JavaScript



// array of strings
var stationary = ["books", "rulers", "pens", "copy", "marker"];

// using stationary.slice(0,2) to slice 
// elements from the stationary array
var sliced_elements = stationary.slice(0, 2);


console.log("After slicing the element from the array, original arrays remain same: ", stationary);

console.log("The sliced array after slicing the element from the array: ",sliced_elements);

Output:

"The original array = " Array [Object { item: "pen", price: 10 }, Object { item: "pencil", price: 5 }, Object { item: "eraser", price: 5 }]
"The popped object from the array = " Object { item: "copy", price: 20 }
0

Explanation: In the above example, we created the stationary array and tried to slice values from it using the stationary.slice(0, 2) command. Now, the sliced elements are stored in the sliced_elements variable, and please note that our original array remained unaffected after this. Finally, we printed the results for the same.

array.filter() function in JavaScript

The JavaScript array.filter() function is used to create a new array which is based upon the filtering criteria provided to the previous array. In this case, only the values that satisfy the filtering criteria are added to the new array and that array is then returned.

The filter() function basically iterates over all the elements of the given array and passes each element to the callback function. After that, the filtering criteria is been checked for the value, and following that, the value is returned to the callback function. In case the callback function returns a True, the element is added to the resultant array.

Syntax:

"The original array = " Array [Object { item: "pen", price: 10 }, Object { item: "pencil", price: 5 }, Object { item: "eraser", price: 5 }]
"The popped object from the array = " Object { item: "copy", price: 20 }
1

Parameters: Let us look into the parameters taken by the filter function in javascript.

  1. Function (Compulsory): It is basically a callback function, which is used to filter out the elements based on the condition provided to them. The callback function has three parameters:

    • element: It is used to hold the value of the array element which is currently processed. It is a mandatory parameter.
    • idx (Optional): It is an optional parameter, and is used to store the index of the current element.
    • arr (Optional): It is the array object on which the function is called.
  2. thisValue (Optional) The thisValue holds the value that is to be used as 'this', during the time of the callback execution. If any value is passed to this thisValue, then it will be used as 'this' for each iteration of the callback function. If not passed, then its default value is set to undefined.

Return Value: A new array that meets the criteria set by the user, is returned by JavaScript's filter function. An empty array is returned if none of the elements satisfies the specified condition.

Code:

"The original array = " Array [Object { item: "pen", price: 10 }, Object { item: "pencil", price: 5 }, Object { item: "eraser", price: 5 }]
"The popped object from the array = " Object { item: "copy", price: 20 }
2

Output:

"The original array = " Array [Object { item: "pen", price: 10 }, Object { item: "pencil", price: 5 }, Object { item: "eraser", price: 5 }]
"The popped object from the array = " Object { item: "copy", price: 20 }
3

Explanation:

In the above example, a filtering condition is used which states that if the value is squared, and it is greater than 30, then return that value. Hence, our filtered array is returned based on that value. In our filtered array, all the elements that specify this condition are stored.

Remove the Last Element by Reducing the Array Size

To remove the last element from the array by reducing the array size, we can use the pop() method as we discussed above. Here, we can directly pop off the last element from the array and the array size will be modified based on that.

How can I remove a specific item from an object in JavaScript?

1. Remove a Property from a JavaScript Object Using the Delete Operator. There is a special operator in JavaScript called the delete operator which can be used to remove a key from Object JavaScript. As the name suggests, the delete operator simply deletes the specified property from the object.

How to add and remove value from object in JavaScript?

Adding/Removing Properties from an Object: For adding any property, one could either use object_name. property_name = value (or) object_name[“property_name”] = value. For deleting any property, one could easily use delete object_name. property_name (or) delete object_name[“property_name”].

How to remove element from object JavaScript by index?

Array findIndex() and splice() methods To remove an element from an array by ID in JavaScript, use the findIndex() method to find the index of the object with the ID in the array. Then call the splice(index, 1) method on the array to remove the object from the array.

How to remove key value from object in JavaScript?

The delete operator is used to delete the key-value pair where the key is “key2”. console. log(obj); The output of the above code in the console will be: { key1: "value1", key3: "value3" }.