- 5 years ago
- Zaid Bin Khalid
- 49,903 Views
-
4
You can delete an element of the array by its value and index with the help of .splice() method. There are other functions also available that you can use to perform the same function. In this tutorial, I will let you know how you can delete an array element by its value.
Furthermore, I will create a complete example that will help you to understand. The .splice() function is used to manipulate the array you can add or delete an element from an array using this function.
You can use several methods to remove item(s) from an Array
- someArray.shift(); // first element removed
- someArray = someArray.slice(1); // first element removed
- someArray.splice(0, 1); // first element removed
- someArray.pop(); // last element removed
- someArray = someArray.slice(0, a.length – 1); // last element removed
- someArray.length = someArray.length – 1; // last element removed
Add Value in a specific position.
Add value to an existing array you can use .splice() function example given below.
//Add values into array
const months = ["Jan", "Feb", "April"];
months.splice(2, 0, "March");
console.log(months);
months.splice(4, 1, "May");
console.log(months);
The output will be:
["Jan", "Feb", "March", "April"]
["Jan", "Feb", "March", "April", "May"]
Remove Value in a specific position.
Remove value to an existing array .splice() function will help you example given below.
var alpha = ['A', 'B', 'C', 'D', 'E'];
var removed = alpha.splice(3, 1);
console.log(alpha);
The output will be:
[“A”, “B”, “C”, “E”]
Remove value from an array by index or value examples are given below.
//Remove from array by value
var arr = [ "abc", "def", "ghi" ];
arr.splice(arr.indexOf("def"), 1);
console.log(arr);
//Remove by index
var arr = [ "abc", "def", "ghi" ];
arr.splice(1, 1);
console.log(arr);
The output will be:
["abc", "ghi"]
["abc", "def"]
You can also use $.grep() function to remove value from array. Of course, this function is depended on JQuery. So before use this function you need to add JQuery lib into your project.
I always use this function to get a difference between the two arrays just like array_diff() a PHP function. The below example explains to you how you get an array difference with the help of JQuery $.grep() function.
//Two array difference
filesAry = [1,2,3,4,5,6,7,8,9,10];
newDelFilesAry = [5,9,1,4];
difference = [];
$.grep(filesAry, function(el) {
if ($.inArray(el, newDelFilesAry) == -1) difference.push(el);
});
console.log(difference);
In the above example, the output will be saved into an array with the name of the difference.
The output will be:
[2, 3, 6, 7, 8, 10]
- 5 years ago
- Zaid Bin Khalid
- 49,903 Views
-
4