简体   繁体   English

JS:按值从数组中删除第一个元素

[英]JS: delete first element from array by value

I have an array: 我有一个数组:

arr = [50, 40, 50, 50];

I need to delete first element, that equal 50 and dont touch another. 我需要删除等于50的第一个元素,并且不要触摸另一个。 This code return only [40] . 此代码仅返回[40]

arr = arr.filter(function(e) {return e !== 50}) // [40]

But I need 但是我需要

arr = arr.somefunction(function(e) {return e !== 50}) // [40, 50, 50]

I would be grateful for any help. 我将不胜感激。

You can use findIndex and splice() 您可以使用findIndexsplice()

 let arr = [50, 40, 50, 50]; arr.splice(arr.findIndex(a => a === 50), 1); console.log(arr) 

If you need it on the prototype of the Array then you can define your custom method. 如果在Array的prototype上需要它,则可以定义自定义方法。

 function removeFirst(cb){ for(let i = 0;i<this.length;i++){ if(cb(this[i],i,this)){ return this.slice(0,i).concat(this.slice(i+1)); } } return this; } Object.defineProperty(Array.prototype,'removeFirst',{ value:removeFirst }) let arr = [50,40,50,50]; let res = arr.removeFirst(x => x === 50); console.log(res) 

You could take a flag and change it of the first value is found. 您可以标记并更改找到的第一个值。

 var array = [40, 40, 50, 40, 50, 40, 50], found = false; array = array.filter(v => found || !(found = v === 50)); console.log(array); 

With a counter, you could specify the amount of value for filtering out. 使用计数器,您可以指定要过滤的值的数量。

 var array = [40, 40, 50, 40, 50, 40, 50], count = 1; array = array.filter(v => !count || (count -= v === 50)); console.log(array); 

findIndex() returns the index of the first occurrence of the function provided. findIndex()返回所提供函数第一次出现的索引。 After that, you can just delete the element using splice(). 之后,您可以使用splice()删除元素。

let arr = [50, 40, 50, 50];
arr.splice(arr.findIndex(function(e) {return e === 50}), 1);
console.log(arr);

You can use a variable to keep track whether you deleted any value or not 您可以使用变量来跟踪是否删除了任何值

 let deleteFirst = (value) => { let arr = [50, 40, 50, 50]; let del = false return arr.filter(val=> { if(val === value && !del){ del = true return false } return true }) } console.log(deleteFirst(50)) console.log(deleteFirst(40)) 

Here's a curried function for that. 这是一个咖喱函数。 It does not modify your original array, returning a new one instead: 它不会修改原始数组,而是返回一个新数组:

 const removeFirst = (val) => ( xs = [], idx = xs .indexOf (val) ) => idx > -1 ? xs .slice (0, idx) .concat ( xs .slice (idx + 1) ) : xs console .log ( removeFirst (50) ([50, 40, 50, 50]) ) 

If you prefer to call it like remove(50, [50, 40, 50, 50]) , then you can just change the first line: 如果您喜欢像remove(50, [50, 40, 50, 50])这样称呼它,则只需更改第一行即可:

const removeFirst = (val, xs = [], idx = xs .indexOf (val) ) => idx > -1
  ? xs .slice (0, idx) .concat ( xs .slice (idx + 1) )
  : xs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM