Lodash中數組常用方法


數組方法

1.數組對象去重 differenceBy(array, [values], [iteratee=_.identity])

let newArr =_.differenceBy(
	[{ name:'cai',age:12 }, { name:'ccc',age:18}, { name:'ddd',age:18}], 
	[{ name:'cai',age:14 }, { name:'bbb',age:18}],
	'name'
);
console.log(newArr)

從第一個數組中刪除與第二個數組中'name'值相同的對象。

2.數組對象去重 differenceWith(array, [values], [comparator])

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
 
let newArr = _.differenceWith(objects, [{ 'x': 2, 'y': 1 }], _.isEqual);

console.log(newArr)

跟第一個方式類似,但是第三個參數為比較器(function類型)。

3.數組刪除前面參數 drop(array, [n=1])

_.drop([1, 2, 3]);
// => [2, 3]
 
_.drop([1, 2, 3], 2);
// => [3]
 
_.drop([1, 2, 3], 5);
// => []
 
_.drop([1, 2, 3], 0);
// => [1, 2, 3]

功能類似於數組中的shift()方法,可以刪除頭部數據。返回值跟shfit()不同,返回值是剩余數組。

4.多個數組求交集, intersection([arrays])

var arr=[1,2,3,4,5,6]
var arr1=[1,2,3,5,7,9]
var arr2=[1,2,4,5,7,9]
let newArr = _.intersection(arr,arr1,arr2);
console.log(newArr); // => [1, 2, 5]

可以傳入多個數組,取出其中相同的值,返回新數組

5.多個數組對象求交集, intersectionBy([arrays])

var arr = [{ name:'cai',age:12 }, { name:'bbb',age:18}, { name:'ddd',age:18}];
var arr1 = [{ name:'cai',age:14 }, { name:'bbb',age:18}];
	
let newArr = _.intersectionBy(arr,arr1,'name');
console.log(newArr); 

可以傳入多個數組,取出某一個對象中屬性相同的值,返回新數組

6.刪除數組中值相同的項,pull(array, [values])

var array = [1, 2, 3, 1, 2, 3];
 
_.pull(array, 2, 3);
console.log(array);
// => [1, 1]

會改變原數組,返回值就是原數組

7.刪除數組對象中指定屬性相同的項,pullAllBy(array, values, [iteratee=_.identity])

var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
 
_.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
console.log(array);
// => [{ 'x': 2 }]

會改變原數組,返回值就是原數組,刪除array中x為1和3的對象

8.刪除數組中的某一項,pullAt(array, [indexes])

var array = [5, 10, 15, 20];
var evens = _.pullAt(array, 1, 3);
 
console.log(array);    // => [5, 15]
 
console.log(evens);    // => [10, 20]

會改變原數組,返回移除元素組成的新數組

9.移除數組中返回為真值的所有元素,並返回移除元素組成的數組。remove(array, [predicate=_.identity])

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]

會改變原數組,返回移除元素組成的新數組

10.自身數組對象去重,這個方法應該挺常用的。.uniqBy(array, [iteratee=.identity])

let arr = _.uniqBy([{ 'x': 2 }, { 'x': 3,'y':2 },{ 'x': 3 }], 'x');
console.log(arr);

如果有相同的x屬性,則會刪除后面出現的,只會留第一個有x屬性的對象

11.兩個數組對象去重,這個方法應該也挺常用的。.xorBy([arrays], [iteratee=.identity])

let arr = _.xorBy(
  [{ name:'cai',age:12 }, { name:'ccc',age:18}, { name:'ddd',age:18}], 
  [{ name:'cai',age:14 }, { name:'bbb',age:18}],
  'name'
);
console.log(arr)


xorBy是將兩個數組合並之后取name不同的值出來,differentBy是比較兩個數組,取不同的值,還有intersectionBy,這幾個應該是開發中常用的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM