JS和Lodash数组查找和删除方法



假设我在js:中有一个数组

let arr = ['one', 'two', 'three', 'four']
  1. 如何搜索数组并检查数组中是否存在'three'元素并返回true/false。

  2. 如何从数组中删除给定的元素(例如"two"(。

这方面有没有lodash方法?

您不需要lodash:

arr.includes("three") // true
arr.includes("five") // false
// the 1 means to delete one element
arr.splice(arr.indexOf("two"), 1)
arr // ["one", "three", "four"]

您需要lodash来实现这些功能吗?取决于。为了将功能性组合物与其他lodash官能团一起应用,使用lodash当量可能是有益的。

香草JS实现:

const targetValue = 'four';
const exampleArray = ['one', 'two', 'three', 'four', 'five'];
// 1) checks whether the exampleArray contains targetValue
exampleArray.includes(targetValue);
// 2) creates a new array without targetValue
const exampleArrayWithoutTargetValue =
exampleArray.filter((value) => value !== targetValue);

使用lodash:

const targetValue = 'four';
const exampleArray = ['one', 'two', 'three', 'four', 'five'];
// 1)
// https://lodash.com/docs/4.17.15#includes
_.includes(exampleArray, targetValue);
// 2)
// https://lodash.com/docs/4.17.15#filter
const exampleArrayWithoutTargetValue =
_.filter(exampleArray, (value) => value !== targetValue);
  1. 检查数组中是否存在元素
arr.inclues("three") //true

如果你想从索引3 开始搜索

arr.inclues("three",3) //false

2.删除给定元素

let arr = ['one', 'two', 'three', 'four']
const index = arr.indexOf('two')
if (index > -1) {
arr.splice(index, 1);
}
console.log(arr)

删除所有出现的给定值

let arr = ['one', 'two', 'three', 'four','two']
let value = 'two'
arr = arr.filter(item => item !== value)
console.log(arr)

如果需要多个值来删除

let arr = ['one', 'two', 'three', 'four']
let toDelete = ['one','three']
arr = arr.filter(item => !toDelete.includes(item))
console.log(arr)

最新更新