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

JS & Lodash array find and delete methods

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

let arr = ['one', 'two', 'three', 'four']
  1. 我将如何搜索数组并检查数组中是否存在 'three' 元素以及 return 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.Delete给定元素

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)