簡體   English   中英

JS & Lodash 數組查找和刪除方法

[英]JS & Lodash array find and delete methods

假設我在 js 中有一個數組:

let arr = ['one', 'two', 'three', 'four']
  1. 我將如何搜索數組並檢查數組中是否存在'three'元素並返回真/假。

  2. 我將如何從數組中刪除給定的元素(例如“兩個”)。

有 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM