Array.prototype.destroy = function(obj){// Return null if no objects were found and removedvar destroyed = null;
for(var i = 0; i < this.length; i++){
// Use while-loop to find adjacent equal objectswhile(this[i] === obj){
// Remove this[i] and store it within destroyeddestroyed = this.splice(i, 1)[0];}}
return destroyed;}
const arrayWithoutFastest = (() => {const isArray = canBeArray => ('isArray' in Array)? Array.isArray(canBeArray): Object.prototype.toString.call(canBeArray) === '[object Array]';
let mapIncludes = (map, key) => map.has(key);let objectIncludes = (obj, key) => key in obj;let includes;
function arrayWithoutFastest(arr, ...thisArgs) {let withoutValues = isArray(thisArgs[0]) ? thisArgs[0] : thisArgs;
if (typeof Map !== 'undefined') {withoutValues = withoutValues.reduce((map, value) => map.set(value, value), new Map());includes = mapIncludes;} else {withoutValues = withoutValues.reduce((map, value) => { map[value] = value; return map; } , {});includes = objectIncludes;}
const arrCopy = [];const length = arr.length;
for (let i = 0; i < length; i++) {// If value is not in exclude listif (!includes(withoutValues, arr[i])) {arrCopy.push(arr[i]);}}
return arrCopy;}
return arrayWithoutFastest;})();
如何使用:
const arr = [1,2,3,4,5,"name", false];
arrayWithoutFastest(arr, 1); // will return array [2,3,4,5,"name", false]arrayWithoutFastest(arr, 'name'); // will return [2,3,4,5, false]arrayWithoutFastest(arr, false); // will return [2,3,4,5]arrayWithoutFastest(arr,[1,2]); // will return [3,4,5,"name", false];arrayWithoutFastest(arr, {bar: "foo"}); // will return the same array (new copy)
var removed = helper.remove(arr, row => row.id === 5 );
var removed = helper.removeAll(arr, row => row.name.startsWith('BMW'));
定义
var helper = {// Remove and return the first occurrence
remove: function(array, predicate) {for (var i = 0; i < array.length; i++) {if (predicate(array[i])) {return array.splice(i, 1);}}},
// Remove and return all occurrences
removeAll: function(array, predicate) {var removed = [];
for (var i = 0; i < array.length; ) {if (predicate(array[i])) {removed.push(array.splice(i, 1));continue;}i++;}return removed;},};
var array = [2, 5, 9, 5];
// Remove last occurrence (or all occurrences)for (var i = array.length; i--;) {if (array[i] === 5) {array.splice(i, 1);break; // Remove this line to remove all occurrences}}
或
var array = [2, 5, 9, 5];
// Remove first occurrencefor (var i = 0; array.length; i++) {if (array[i] === 5) {array.splice(i, 1);break; // Do not remove this line}}
var myArray = [1,2,3,4,5]; // First array
var removeItem = function(array,value) { // My clear functionif(Array.isArray(value)) { // For multi removefor(var i = array.length - 1; i >= 0; i--) {for(var j = value.length - 1; j >= 0; j--) {if(array[i] === value[j]) {array.splice(i, 1);};}}}else { // For single removefor(var i = array.length - 1; i >= 0; i--) {if(array[i] === value) {array.splice(i, 1);}}}}
removeItem(myArray,[1,4]); // myArray will be [2,3,5]
/*** Removes all occurences of the item from the array.** Modifies the array “in place”, i.e. the array passed as an argument* is modified as opposed to creating a new array. Also returns the modified* array for your convenience.*/function removeInPlace(array, item) {var foundIndex, fromIndex;
// Look for the item (the item can have multiple indices)fromIndex = array.length - 1;foundIndex = array.lastIndexOf(item, fromIndex);
while (foundIndex !== -1) {// Remove the item (in place)array.splice(foundIndex, 1);
// BookkeepingfromIndex = foundIndex - 1;foundIndex = array.lastIndexOf(item, fromIndex);}
// Return the modified arrayreturn array;}
Vanilla JavaScript(ES5.1)-不可变版本
浏览器支持:与vanilla JavaScript就地版相同
/*** Removes all occurences of the item from the array.** Returns a new array with all the items of the original array except* the specified item.*/function remove(array, item) {var arrayCopy;
arrayCopy = array.slice();
return removeInPlace(arrayCopy, item);}
/*** Removes all occurences of the item from the array.** Returns a new array with all the items of the original array except* the specified item.*/function remove(array, item) {// Copy the arrayarray = [...array];
// Look for the item (the item can have multiple indices)let fromIndex = array.length - 1;let foundIndex = array.lastIndexOf(item, fromIndex);
while (foundIndex !== -1) {// Remove the item by generating a new array without itarray = [...array.slice(0, foundIndex),...array.slice(foundIndex + 1),];
// BookkeepingfromIndex = foundIndex - 1;foundIndex = array.lastIndexOf(item, fromIndex)}
// Return the new arrayreturn array;}
/*** Removes one instance of `value` from `array`, without mutating the original array. Uses loose comparison.** @param {Array} array Array to remove value from* @param {*} value Value to remove* @returns {Array} Array with `value` removed*/export function arrayRemove(array, value) {for(let i=0; i<array.length; ++i) {if(array[i] == value) {let copy = [...array];copy.splice(i, 1);return copy;}}return array;}
const a = {'field': 2} // Non-primitive objectconst b = {'field': 2} // Non-primitive object with same valueconst c = a // Non-primitive object that reference the same object as "a"
assert(a !== b) // Don't reference the same item, but have same valueassert(a === c) // Do reference the same item, and have same value (naturally)
//Note: there are many alternative implementations for valuesAreEqualfunction valuesAreEqual (x, y) {return JSON.stringify(x) === JSON.stringify(y)}
//filter will delete false values//Thus, we want to return "false" if the item// we want to delete is equal to the item in the arrayfunction removeFromArray(arr, toDelete){return arr.filter(target => {return !valuesAreEqual(toDelete, target)})}
const exampleArray = [a, b, b, c, a, {'field': 2}, {'field': 90}];const resultArray = removeFromArray(exampleArray, a);
//resultArray = [{'field':90}]
function removeElement(idx, arr) {// Check the index valueif (idx < 0 || idx >= arr.length) {return;}// Shift the elementsfor (var i = idx; i > 0; --i) {arr[i] = arr[i - 1];}// Remove the first element in arrayarr.shift();}
function uniq(array) {var len = array.length;var dupFree = [];var tempObj = {};
for (var i = 0; i < len; i++) {tempObj[array[i]] = 0;}
console.log(tempObj);
for (var i in tempObj) {var element = i;if (i.match(/\d/)) {element = Number(i);}dupFree.push(element);}
return dupFree;}
const arr = [ 1, 2, 55, 3, 2, 4, 55 ];const f = function( acc, val, currIndex ){// We have not seen this value before: make a bucket... NB: although val's typeof is 'number',// there is seamless equivalence between the object key (always string)// and this variable val.! ( val in acc ) ? acc[ val ] = []: 0;// Drop another array index in the bucketacc[ val ].push( currIndex );return acc;}const myIntsMapObj = arr.reduce( f, {});
console.log( myIntsMapObj );
我刚刚通过Object.defineProperty在Array.prototype上创建了一个Poly填充,以删除数组中所需的元素,而不会在稍后通过for .. in ..迭代它时导致错误
if (!Array.prototype.remove) {// Object.definedProperty is used here to avoid problems when iterating with "for .. in .." in Arrays// https://stackoverflow.com/questions/948358/adding-custom-functions-into-array-prototypeObject.defineProperty(Array.prototype, 'remove', {value: function () {if (this == null) {throw new TypeError('Array.prototype.remove called on null or undefined')}
for (var i = 0; i < arguments.length; i++) {if (typeof arguments[i] === 'object') {if (Object.keys(arguments[i]).length > 1) {throw new Error('This method does not support more than one key:value pair per object on the arguments')}var keyToCompare = Object.keys(arguments[i])[0]
for (var j = 0; j < this.length; j++) {if (this[j][keyToCompare] === arguments[i][keyToCompare]) {this.splice(j, 1)break}}} else {var index = this.indexOf(arguments[i])if (index !== -1) {this.splice(index, 1)}}}return this}})} else {var errorMessage = 'DANGER ALERT! Array.prototype.remove has already been defined on this browser. 'errorMessage += 'This may lead to unwanted results when remove() is executed.'console.log(errorMessage)}
删除整数值
var a = [1, 2, 3]a.remove(2)a // Output => [1, 3]
删除字符串值
var a = ['a', 'ab', 'abc']a.remove('abc')a // Output => ['a', 'ab']
删除布尔值
var a = [true, false, true]a.remove(false)a // Output => [true, true]
Array.prototype.remove = function(data) {const dataIdx = this.indexOf(data)if(dataIdx >= 0) {this.splice(dataIdx ,1);}return this.length;}
let a = [1,2,3];// This will change arr a to [1, 3]a.remove(2);
Array.prototype.remove = function(item) {// 'index' will have -1 if 'item' does not exist,// else it will have the index of the first item found in the arrayvar index = this.indexOf(item);
if (index > -1) {// The splice() method is used to add/remove items(s) in the arraythis.splice(index, 1);}return index;}
var arr = [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];
// Printing array// [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];console.log(arr)
// Removing 67 (getting its index, i.e. 2)console.log("Removing 67")var index = arr.remove(67)
if (index > 0){console.log("Item 67 found at ", index)} else {console.log("Item 67 does not exist in array")}
// Printing updated array// [ 11, 22, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];console.log(arr)
// ............... Output ................................// [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4 ]// Removing 67// Item 67 found at 2// [ 11, 22, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4 ]
let arr = [1, 2, 3, 4, 5, 6];let del = 4;if (arr.indexOf(4) >= 0) {arr.splice(arr.indexOf(4), 1)}
或
let del = 4;for(var i = arr.length - 1; i >= 0; i--) {if(arr[i] === del) {arr.splice(i, 1);}}
If you know the element alone but not the position (or index) of the element, and want to delete just very first matching element using splice() method:
let arr = [1, 11, 2, 11, 3, 4, 5, 11, 6, 11];
for (let i = 0; i < arr.length-1; i++) {if ( arr[i] === 11) {arr.splice(i, 1);break;}}console.log(arr);// [1, 11, 2, 11, 3, 4, 5, 11, 6, 11]
function getIndex($id){return (this.removeIndex($id)alert("This element was removed"))}
function removeIndex(){const index = $id;this.accesor.id.splice(index.id) // You can use splice for slice index on// accessor id and return with message}
var colors = ["red","blue","car","green"];var carIndex = colors.indexOf("car"); // Get "car" index// Remove car from the colors arraycolors.splice(carIndex, 1); // colors = ["red", "blue", "green"]
var num = [5, 6, 5, 4, 5, 1, 5];
var result1 = num.filter((el, index) => el != 5) // for remove all 5var result2 = num.filter((el, index) => index != 5) // for remove item with index == 5
console.log(result1);console.log(result2);
There is no native 'array.remove' method in JavaScript, but we can create one using above methods we used as implemented in the following code snippet.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function arrayRemove(arr, value) {
return arr.filter(function(element) {return element != value;});}
console.log("Original array: " + array);console.log("Modified array: " + arrayRemove(array, 6)); // 6 is removed
// remove by value. return true if value found and removed, false otherwiseArray.prototype.remove = function(val){return this.includes(val) && !!this.splice(this.indexOf(val), 1);}
let someArr = [...Array(99999).keys()]
console.time('filter')someArr.filter(x => x !== 6666)console.timeEnd('filter')
console.time('splice by indexOf')someArr.splice(someArr.indexOf(6666), 1)console.timeEnd('splice by indexOf')
let data = [];data.__proto__.remove = (n) => { data = data.flatMap((v) => { return v !== n ? v : []; }) };
data = [1, 2, 3];data.remove(2);console.log(data); // [1,3]
data = ['a','b','c'];data.remove('b');console.log(data); // [a,c]
Array.prototype.removeByIndex = function(i) {if(!Number.isInteger(i) || i < 0) {// i must be an integerreturn this;}
return this.filter((f, indx) => indx !== i)}var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];
var b = a.removeByIndex(2);console.log(a);console.log(b);
有时我们不知道元素的索引。
Array.prototype.remove = function(i) {return this.filter(f => f !== i)}var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];
var b = a.remove(5).remove(null);console.log(a);console.log(b);
// It removes all occurrences of searched value
function RemoveEmptyItems(arr) {var result = [];for (var i = 0; i < arr.length; i++) if (arr[i] != null && arr[i].length > 0) result.push(arr[i]);return result;}
用法:
var arr = [1,2,3, "", null, 444];arr = RemoveEmptyItems(arr);console.log(arr);
const removeItem =idx =>arr =>arr.reduce((acc, a, i) => idx === i ? acc : acc.concat(a), [])
const array = [1, 2, 3]const index = 1
const newArray = removeItem(index)(array)
console.log(newArray) // logs the following array to the console : [1, 3]
…或者一个递归函数(老实说,这不是那么优雅……也许有人有更好的递归解决方案??)…
const removeItemPrep =acc =>i =>idx =>arr =>
// If the index equals i, just feed in the unchanged accumulator(acc) else...i === idx ? removeItemPrep(acc)(i + 1)(idx)(arr) :
// If the array length + 1 of the accumulator is smaller than the array length of the original array concatenate the array element at index i else...acc.length + 1 < arr.length ? removeItemPrep(acc.concat(arr[i]))(i + 1)(idx)(arr) :
// return the accumulatoracc
const removeItem = removeItemPrep([])(0)
const array = [1, 2, 3]const index = 1
const newArray = removeItem(index)(array)
console.log(newArray) // logs the following array to the console : [1, 3]
const array = [1,2,3,4,5,6,7,8,9,0];const index = array.indexOf(5);// find Index of specific numberif(index != -1){array.splice(index, 1); // remove number using index}console.log(array);
var arr = [1,2,3,4]// Let's say we have the index, coming from some APIlet index = 2;// splice is a destructive method and modifies the original arrayarr.splice(2, 1)
如果您没有索引而只有值:在这种情况下,您可以使用filter
// Let's remove '2', for examplearr = arr.filter((value)=>{return value !== 2;})
const heartbreakerArray = ["😂","❤️","😍","❤️","❤️"]
// 1. If you want to remove only the first element from the arrayconst shallowCopy = Array.from(heartbreakerArray)const index = shallowCopy.indexOf("❤️")if (index > -1) { shallowCopy.splice(index, 1) }
console.log(shallowCopy) // Array(2) ["😂","😍","❤️","❤️"]
// 2. If you want to remove all matched elements from the arrayconst myOutputArray = []const mySearchValue = "❤️"for(let i = 0; i < heartbreakerArray.length; i++){if(heartbreakerArray[i]!==mySearchValue) {myOutputArray.push(heartbreakerArray[i])}}
console.log(myOutputArray) // Array(2) ["😂","😍"]
// Original arrayconst arr = [1,2,2,3,2,5,6,7];
// Remove all 2s from arrayarr.remove(2); // [1,3,5,6,7]
// Remove one 2 from beginning of arrayarr.remove(2, 1); // [1,2,3,2,5,6,7]
// Remove two 2s from beginning of arrayarr.remove(2, 2); // [1,3,2,5,6,7]