javascript九种方法从数组中删除元素

JavaScript数组Array的使用:添加、删除、排序、遍历、互转 数组是存储于一个连续空间且具有相同数据类型的元素集合。可以把数组看作一张单行表格,该表格的每一个单元格都可以存储一个数据,而且各单元格中存储的数据类型可以不同。这些单元格被称为数组元素,每个数组元素都有一个索引号,通过索引号可以方便地引用数组元素。数组是 JavaScript 中唯一用来存储和操作有序数据集的数据结果。数组是 JavaScript 中十分常用的一种数据类型。数组提供了一种快速、方便地管理一组相关数据的方法,是 JavaScript 程序设计的重要内容。通过数组可以对大量性质相同的数据进行存储 阅读详情

JavaScript arrays allow you to group values and iterate over them. You can add and remove array elements in different ways. Unfortunately there is not a simple Array.remove method.

So, how do you delete an element from a JavaScript array?

Instead of a delete method, the JavaScript array has a variety of ways you can clean array values.

You can remove elements from the end of an array using pop, from the beginning using shift, or from the middle using splice. The JavaScript Array filter method to create a new array with desired items, a more advanced way to remove unwanted elements.

There are different methods and techniques you can use to remove elements from JavaScript arrays:

  • pop - Removes from the End of an Array
  • shift - Removes from the beginning of an Array
  • splice - removes from a specific Array index
  • filter - allows you to programatically remove elements from an Array

You will also learn some other ways you can remove elements from an array that may not be so obvious, like with LoDash.

Removing Elements from End of a JavaScript Array

JavaScript Array elements can be removed from the end of an array by setting the length property to a value less than the current value. Any element whose index is greater than or equal to the new length will be removed.

var ar = [1, 2, 3, 4, 5, 6];
ar.length = 4; // set length to remove elements
console.log( ar ); //  [1, 2, 3, 4]

The pop method removes the last element of the array, returns that element, and updates the length property. The pop method modifies the array on which it is invoked, This means unlike using delete the last element is removed completely and the array length reduced.

var ar = [1, 2, 3, 4, 5, 6];
ar.pop(); // returns 6
console.log( ar ); // [1, 2, 3, 4, 5]

Removing Elements from Beginning of a JavaScript Array

How do you remove the first element of a JavaScript array?

The shift method works much like the pop method except it removes the first element of a JavaScript array instead of the last.

There are no parameters since the shift method only removed the first array element. When the element is removed the remaining elements are shifted down.

var ar = ['zero', 'one', 'two', 'three'];
ar.shift(); // returns "zero"
console.log( ar ); // ["one", "two", "three"]

The shift method returns the element that has been removed, updates the indexes of remaining elements, and updates the length property. It modifies the array on which it is invoked.

If there are no elements, or the array length is 0, the method returns undefined.

Using Splice to Remove Array Elements in JavaScript

The splice method can be used to add or remove elements from an array. The first argument specifies the location at which to begin adding or removing elements. The second argument specifies the number of elements to remove. The third and subsequent arguments are optional; they specify elements to be added to the array.

Here we use the splice method to remove two elements starting from position three (zero based index):

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
var removed = arr.splice(2,2);

/*
removed === [3, 4]
arr === [1, 2, 5, 6, 7, 8, 9, 0]
*/

An array containing the removed elements is returned by the splice method. You can see the removed array contains [3, 4] and the original array contains the remaining values.

The splice method can also be used to remove a range of elements from an array.

["bar", "baz", "foo", "qux"]

list.splice(0, 2) 
// Starting at index position 0, remove two elements ["bar", "baz"] and retains ["foo", "qux"].

Removing Array Items By Value Using Splice

If you know the value you want to remove from an array you can use the splice method. First you must identify the index of the target item. You then use the index as the start element and remove just one element.

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

for( var i = 0; i < arr.length; i++){ 
   if ( arr[i] === 5) {
     arr.splice(i, 1); 
   }
}

//=> [1, 2, 3, 4, 6, 7, 8, 9, 0]

This is a simple example where the elements are integers. If you have an array of objects you would need a more sophisticated routine.

This works if you only want to remove a single item. If you want to remove multiple items that match your criteria there is a glitch.

As the items are removed from the array the index still increments and the next item after your matched value is skipped.

The simple solution is to modify the above example to decrement the index variable so it does not skip the next item in the array.

var arr = [1, 2, 3, 4, 5, 5, 6, 7, 8, 5, 9, 0];

for( var i = 0; i < arr.length; i++){ 
   if ( arr[i] === 5) {
     arr.splice(i, 1); 
     i--;
   }
}

//=> [1, 2, 3, 4, 6, 7, 8, 9, 0]

In the modified example I added 2 additional 5 values to the array. I also added 'i--;' after the splice call.

Now when you execute the loop it will remove every matching item.

Thanks to Kristian Sletten for pointing out the issue with the loop skipping the following item.

Using the Array filter Method to Remove Items By Value

Unlike the splice method, filter creates a new array. filter() does not mutate the array on which it is called, but returns a new array.

filter() has a single parameter, a callback method. The callback is triggered as the filter method iterates through the array elements. It will pass three values to the callback: the current value or element, the current array index and the full array.

The callback method should return either true or false. It is your responsibility to test the value (element) to see if it meets your criteria. If it does you can return true. Elements that return true are added to the new, filtered array.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

var filtered = array.filter(function(value, index, arr){

    return value > 5;

});

//filtered => [6, 7, 8, 9]
//array => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

You should note a new array containing matching values is returned. The original array is left untouched. I find this useful because I often want to retain an original data source, but retrieve subsets based on different logic sets.

The Lodash Array Remove Method

Sometimes utility libraries are the best way to solve more complex problems. Lodash provides a rich set of array manipulation methods, one being remove.

The Lodash remove method works much like the array filter method, but sort of in reverse. It does not save the original array values, but removes matching elements. It returns the matching elements as a new array.

var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
  return n % 2 === 0;
});

console.log(array);
// => [1, 3]

console.log(evens);
// => [2, 4]

Making a Remove Method

As I mentionmed before, there is no native Array.remove method. The Lodash method does solve this problem, but you may not always want to use Lodash. This does not mean you cannot create a utility method. John Resig gave us a model to follow, however he extended the Array prototype, which is a bad idea.

Instead I created an Array remove utility method that can be added to a helper or utility library. Like the Lodash remove method the first parameter is the target array. It uses Array.filter to return elements not matching a value.

function arrayRemove(arr, value) {

   return arr.filter(function(ele){
       return ele != value;
   });

}

var result = arrayRemove(array, 6);

// result = [1, 2, 3, 4, 5, 7, 8, 9, 0]

This method is simple, it assumes simple values like numbers or strings. You could modify this method to use a custom comparison method, but I think it would be easier to just use the filter method directly.

 

Explicitly Remove Array Elements Using the Delete Operator

You can remove specific array elements using the delete operator:

var ar = [1, 2, 3, 4, 5, 6];
delete ar[4]; // delete element with index 4
console.log( ar ); // [1, 2, 3, 4, undefined, 6]
alert( ar ); // 1,2,3,4,,6

Using the delete operator does not affect the length property. Nor does it affect the indexes of subsequent elements. The array becomes sparse, which is a fancy way of saying the deleted item is not removed but becomes undefined. Compare using delete with the splice method described below.

The delete operator is designed to remove properties from JavaScript objects, which arrays are objects.

The reason the element is not actually removed from the array is the delete operator is more about freeing memory than deleting an element. The memory is freed when there are no more references to the value.

Clear or Reset a JavaScript Array

What if you want to empty an entire array and just dump all of it's elements?

There are a couple of techniques you can use to create an empty or new array.

The simplest and fastest technique is to set an array variable to an empty array:

var ar = [1, 2, 3, 4, 5, 6];

//do stuff

ar = [];

//a new, empty array!

The problem this can create is when you have references to the variable. The references to this variable will not change, they will still hold the original array's values. This of course can create a bug?.

This is an over simplified example of this scenario:

var arr1 = [1, 2, 3, 4, 5, 6];

var arr2 = arr1;  // Reference arr1 by another variable 

arr1 = [];

console.log(arr2); // Output [1, 2, 3, 4, 5, 6]

A simple trick to clear an array is to set its length property to 0.

var ar = [1, 2, 3, 4, 5, 6];

console.log(ar); // Output [1, 2, 3, 4, 5, 6]

ar.length = 0;

console.log(ar); // Output []

Another, sort of unnatural technique, is to use the splice method, passing the array length as the 2nd parameter. This will return a copy of the original elements, which may be handy for your scenario.

var ar = [1, 2, 3, 4, 5, 6];

console.log(ar); // Output [1, 2, 3, 4, 5, 6]

ar.splice(0, ar.length);

console.log(ar); // Output []

The last two techniques don't create a new array, but change the array's elements. This means references should also update.

There is another way, using a while loop. It feels a little odd to me, but at the same time looks fancy, so it may impress some friends!

var ar = [1, 2, 3, 4, 5, 6];

console.log(ar); // Output [1, 2, 3, 4, 5, 6]

  while (ar.length) {
    ar.pop();
  }

console.log(ar); // Output []

Not a way I would go about clearing a JavaScript array, but it works and it is readable. Some performance test have also shown this to be the fastest technique, so maybe it is better than I originally thought!

Summary

Removing JavaScript Array items is important to managing your data. There is not a single 'remove' method available, but there are different methods and techniques you can use to purge unwanted array items.

This article has reviewed these methods and how they can be used. You also saw how to create a helper method that makes removing items from an array a bit easier and consistent.

Thanks to Rob Sherwood for pointing out some syntactical typos!

 

 

javascript-remove-from-array

Python爬虫实战:绕过B站-352风控的完整解决方案 网络爬虫技术是数据采集和自动化测试的重要工具,其核心原理是通过模拟HTTP请求获取网页数据。在实践过程中,开发者常会遇到网站反爬机制,这涉及请求指纹识别、IP行为分析等安全技术。这些风控措施的价值在于保护网站数据安全和服务器资源,广泛应用于电商、社交、内容平台等场景。针对B站等平台的-352风控错误,需要综合运用请求头伪装、会话管理、参数签名破解等技术方案。本文重点探讨如何通过构建完整的浏览器级请求头、管理Cookie会话、以及使用Playwright等浏览器自动化工具,有效解决Python爬虫在B站数据采 阅读详情

相关推荐

别再为格式发愁:safetensors转GGUF的三种高效方法及Ollama集成对比

本文详细介绍了将safetensors格式转换为GGUF格式的三种高效方法,包括llama.cpp原生转换、GGUF官方工具链和Transformers中转方案,并对比了它们在Ollama集成中的表现。文章还提供了实际项目中的踩坑经验和性能调优建议,帮助开发者快速掌握模型转换技术。

weixin_42651281的博客 640

JavaScript数组添加remove()方法

<br />第一种:Javascript代码 //Array Remove - By John Resig (MIT Licensed)   Array.prototype.remove = function(from, to) {       var rest = this.slice((to || from) + 1 || this.length);       this.length = from < 0 ? this.length + from : from;       return this.p

我的地盘 1万+

3D Slicer隐藏技巧:这样玩转医学影像分割与3D建模(含DICOM处理)

本文深入探讨3D Slicer在医学影像分割与3D建模中的高级应用技巧,包括多模态分割策略、三维可视化优化及DICOM数据处理。通过专业配置和Python脚本示例,帮助医疗AI开发者和影像科医师提升工作效率,实现精准的医学图像分析与建模。

weixin_28559803的博客 432

JavaScript Array Remove 最好的删除数组元素的方法

为什么80%的码农都做不了架构师?>>> ...

weixin_33851604的博客 315

【鸿蒙南向开发】OpenHarmony——分布式数据对象之功能实践

通过本文的学习可了解到分布式数据对象的主要接口、大致调用方法和功能实现等。结合对应内容,可以进一步对分布式数据对象同步机制做深度学习。下一步,(1) 着重理解同步组网的构建原理。(2) 着重理解同步组网内,监听change和status变化的实现。●如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:●关注小编,同时可以期待后续文章ing🚀,不定期分享原创知识。

HarmonyOS_666的博客 1089

机器学习模型系列:随机森林的原理和示例介绍

让我们总结一下与其他监督式机器学习模型相比,随机森林的优缺点。优点在许多真实数据集上已知能提供高度准确的模型。通过结合多个决策树的预测,可以捕捉数据集中的复杂交互和模式。通过自动选择相关特征,可以有效处理高维数据集。与单个决策树相比,不容易过拟合。自助采样和每个节点的随机特征选择有助于减少过拟合并改善泛化能力。可以处理包括数值和分类特征在内的异构数据类型。可以处理缺失值而不需要填充。提供特征重要性的度量。集成中的树可以并行训练,因为每个决策树可以独立构建。模型的泛化误差具有理论上的界限。

数智笔记 1万+

javascript删除数组中的几种方式

JavaScript数组中删除元素

tutodelinglimgho的博客 1万+

NR/5G - On demand SI

NR中系统消息如MIB -可用于无线帧同步等,SIB1 -小区物理信道公共配置等,是驻留一个小区所必需获得的信息,这类系统信息小区是进行周期性广播。 在SI的配置中,系统消息分为BroadCasting和non-BroadCasting,BroadCasting类系统消息基站也是周期性进行广播的,而non-BroadCasting类系统消息则是通过一种on-demand的方式,即如果需要读取这类系统消息,那么UE需要先发送请求给基站,基站响应UE之后,再下发系统消息。 ...

6775

数组删除元素使用remove最优的方法

【代码】数组删除元素使用remove最优的方法。

qq_39691676的博客 360

3DMax马克杯制作教程

01 在前视图创建一个【圆柱体】,设置参数,长度为32,高度为82;高度分段12、边数为16;如图所示。 02 点击鼠标右键,把圆柱体转换为可编辑多边形,如图所示。 03 在修改面板中,选择【多边形】层级,在视图中选择所示的面,使用缩放工具稍微缩小一点,如图所示。 04 点击【插入设置】,如图所示。 设置插入数量为2.5mm。 05 点击【挤出设置】,如图所示。 ...

youximoxingEDO的博客 3477

STM32实战开发(66):STM32图像处理开发教程

随着物联网、人工智能和嵌入式技术的不断发展,图像处理技术在嵌入式系统中的应用越来越广泛。图像处理不仅在视觉识别、安防监控、智能家居等领域中发挥着重要作用,也在工业自动化、医疗成像、无人驾驶等高科技领域中占据重要地位。而STM32凭借其强大的硬件性能和丰富的外设支持,成为了许多图像处理应用的理想平台。

2201_76125393的博客 1444

javascript数组去重的9种方法(思路)

1.新建空数组,遍历原数组和新数组,如果数组元素和新数组元素相等则不push ​ function fn1 (arr) { var newArr = []; for (var i = 0,len = arr.length; i < len; i ++) { if (newArr.length !== 0) { var canPush = tru...

bc492010874的博客 367

大模型应用开发 100 天:Python + LLM 从入门到精通 day01~环境搭建与开发工具

Day 1 正式开启《大模型应用开发 100 天》实战旅程。本文聚焦 AI 开发最容易被忽视却至关重要的环境搭建环节,系统讲解基于 pyenv、uv、VS Code 构建一套可复现、项目隔离的标准化 Python 开发工具链。你将掌握多 Python 版本管理、极速依赖安装、虚拟环境隔离、代码规范配置完整流程,配套可直接运行的环境校验脚本与 Mermaid 架构图,规避版本冲突、环境污染等高频踩坑问题,为后续 99 天 LLM 项目开发筑牢底层基础。来自华北理工大学段一凡的博客文章

段一凡的博客 245

改变原数组的9个方法

改变原数组的9个方法 1. splice() 可从数组中添加/删除数据 2. reverse() 颠倒数组中元素的顺序 3. fill() 可将数组中所有元素都设为相同的值 4. copyWithin() 从数组的指定位置拷贝元素到数组的另一个指定位置中 5. sort() 按照字典序来排顺序 6. push() 向数组末尾添加一个或者多个元素,从而扩展数组 7. pop() 删除数组末尾数据 8. unshift() 向数组开头添加一个或者多个元素,从而扩展数组 9. shift() 删除

小P孩的博客 585

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

js数组去重(9种方法),你都会了吗?

九种数组去重的方式和详解(包含对象数组去重)

前端菜鸟好先森的博客 8万+

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

JS中数组去重的九种方式

一、利用ES6中的Set方法去重 Set为ES6中新增的对象,允许存储任何类型(原始值或引用值)的唯一值 let arr = [1,0,0,2,9,8,3,1]; function unique(arr) { return Array.from(new Set(arr)) } console.log(unique(arr)); // [1,0,2,9,8,3]  or6      console.log(...n

马小兜要努力呀 258

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

JS数组去重的九种高阶方法

一般的方法此处也不列举了,还是有很多的,如双层循环判断是否相等,或新建数组比较再push等等,需要注意的是,使用splice方法移除元素时,有可能会导致数组塌陷问题,需要处理一下 本文中介绍了多种数组去重的方法,使用了较多的高阶方法及API,并给出相应解释及语法,还有其他多种组合调用方式,原理逻辑其实都差不多,其中for循环可以与forEach方法相互转换,因此此处便不再一一列举,大家如果有更好的算法,可以留言给我,虚心请教!! 给定一个数组 [1,2,2,4,null,null,'3','abc',3,

高先生的猫 356

javascript之九种数组去重的方法

数组去重,第一反应就是for循环,如果一个for循环解决不了,那就多来几个。。。哈哈,心血来潮查了下数组去重的方法,是我见识短浅。以下,我将介绍九种js中数组去重的方法: 利用 ES6 Set去重 利用splice()去重 利用indexOf()去重 利用sort()去重 利用 对象的属性不能相同的特性进行数组去重 利用includes() 利用hasOwnProp...

The_upside_of_down的博客 333

JS解决数组去重的多种方法

JS 数组去重 9种办法 利用key 的唯一性 交换元素位置从而替换掉 splice 方法 Array.fliter + Array.indexOf Array.fliter + Object.hasOwnProperty Array.reduce + Array.includes Array.indexOf Array.includes new Set + 扩展运算符 || Array.from new Map 给定一个数组 [1,2,2,4,null,null,‘3’,‘abc’,3,5,4,1

weixin_43403124的博客 1141

数组去重的九种方法

数组去重的九种方法

m0_74089929的博客 444

JavaScript 数组去重的高阶方法

JavaScript 数组去重的高阶方法(9种) 一般的方法此处也不列举了,还是有很多的,如双层循环判断是否相等,或新建数组比较再push等等,需要注意的是,使用splice方法移除元素时,有可能会导致数组塌陷问题,需要处理一下。 本文中介绍了多种数组去重的方法,使用了较多的高阶方法及API,并给出相应解释及语法,还有其他多种组合调用方式,原理逻辑其实都差不多,其中for循环可以与forEach方法相互转换,因此此处不再一一列举 给定一个数组 [1,2,2,4,null,null,‘3’,‘abc’,3,5

weixin_50313248的博客 406

js数组去重(9种方法)搬运自:前端菜鸟好先森

js数组去重(9种方法)搬运自:前端菜鸟好先森

MoFe1的博客 4837

java javascript数组_JavaScript 数组方法

数组方法:1、Array.join([param]) 方法:将数组中所有的元素都转换为字符串并连接起来,通过字符 param 连接,默认使用逗号,返回最后生成的字符串2、Array.reverse() 方法:将数组中的元素颠倒顺序(在原数组中重新排列它们),返回逆序数组3、Array.sort([function]) 方法:将数组中的元素按字母表顺序排序并返回排序后的数组,可选参数 functio...

weixin_36323390的博客 264

javascript数组去重有几种方式

一、利用ES6中的 Set 方法去重 注:Set为ES6新增的一个对象,允许存储任何类型(原始值或引用值)的唯一值 let arr = [1,0,0,2,9,8,3,1]; function unique(arr) { return Array.from(new Set(arr)) } console.log(unique(arr)); // [1,0,2,9,8,3]  or6      conso...

qq_29910567的博客 1057

Js中数组去重的几种方法

  前几天在看前端面试题的时候,其中js部分有个问题是实现数组去重的算法,一开始就想了一两种方法,后来仔细回忆了下这个题,觉得该问题实现方法确实不止局限于一两种方法 ,从不同的角度去看待该问题就会有多种实现方法。以下列举了一些常用方法。 一、利用ES6中的 Set 方法去重   注:Set为ES6新增的一个对象,允许存储任何类型(原始值或引用值)的唯一值 1      let...

weixin_30807677的博客 171

常用数组去重(九种)

小菜鸟在摸鱼

MoXinXueWEB的博客 772
上一篇: Vue动态加载巨量模板组件
下一篇: MongoDB的shell小工具-通过关联值更新collection
java_augur
博客等级 码龄22年 67粉丝 64原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值