是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
一个非常干净的解决方案工作在所有浏览器,没有任何框架是分配一个新的数组,并简单地返回它没有你想删除的项:
/**
* @param {Array} array the original array with all items
* @param {any} item the time you want to remove
* @returns {Array} a new Array without the item
*/
var removeItemFromArray = function(array, item){
/* assign a empty array */
var tmp = [];
/* loop over all array items */
for(var index in array){
if(array[index] !== item){
/* push to temporary array if not like item */
tmp.push(array[index]);
}
}
/* return the temporary array */
return tmp;
}
其他回答
一个非常干净的解决方案工作在所有浏览器,没有任何框架是分配一个新的数组,并简单地返回它没有你想删除的项:
/**
* @param {Array} array the original array with all items
* @param {any} item the time you want to remove
* @returns {Array} a new Array without the item
*/
var removeItemFromArray = function(array, item){
/* assign a empty array */
var tmp = [];
/* loop over all array items */
for(var index in array){
if(array[index] !== item){
/* push to temporary array if not like item */
tmp.push(array[index]);
}
}
/* return the temporary array */
return tmp;
}
//This function allows remove even array from array
var removeFromArr = function(arr, elem) {
var i, len = arr.length, new_arr = [],
sort_fn = function (a, b) { return a - b; };
for (i = 0; i < len; i += 1) {
if (typeof elem === 'object' && typeof arr[i] === 'object') {
if (arr[i].toString() === elem.toString()) {
continue;
} else {
if (arr[i].sort(sort_fn).toString() === elem.sort(sort_fn).toString()) {
continue;
}
}
}
if (arr[i] !== elem) {
new_arr.push(arr[i]);
}
}
return new_arr;
}
使用实例
var arr = [1, '2', [1 , 1] , 'abc', 1, '1', 1];
removeFromArr(arr, 1);
//["2", [1, 1], "abc", "1"]
var arr = [[1, 2] , 2, 'a', [2, 1], [1, 1, 2]];
removeFromArr(arr, [1,2]);
//[2, "a", [1, 1, 2]]
你可以使用without或pull from Lodash:
const _ = require('lodash');
_.without([1, 2, 3, 2], 2); // -> [1, 3]
var remove = function(array, value) {
var index = null;
while ((index = array.indexOf(value)) !== -1)
array.splice(index, 1);
return array;
};
当你需要移除一个在数组中多次出现的值时(例如。[1,2,2,2,4,5,6])。
function removeFrmArr(array, element) {
return array.filter(e => e !== element);
};
var exampleArray = [1,2,3,4,5];
removeFrmArr(exampleArray, 3);
// return value like this
//[1, 2, 4, 5]
可以使用splice从数组中删除单个元素,但splice不能从数组中删除多个相似的元素。
function singleArrayRemove(array, value){
var index = array.indexOf(value);
if (index > -1) array.splice(index, 1);
return array;
}
var exampleArray = [1,2,3,4,5,5];
singleArrayRemove(exampleArray, 5);
// return value like this
//[1, 2, 3, 4, 5]