1. 程式人生 > 實用技巧 >ubuntu進行dpkg安裝時出現xxx依賴於xxx,然而:未安裝軟體包解決方法

ubuntu進行dpkg安裝時出現xxx依賴於xxx,然而:未安裝軟體包解決方法

陣列物件去重

需求:

多組陣列元素組合拼接,最終導致陣列中有一些重複出現的元素。現將陣列中重複的元素剔除掉,最終得到一組沒有重複資料的新陣列物件。

解決方法:

採用 reduce() 處理陣列元素,達到最終目的;

  • reduce()方法接收一個函式作為累加器,陣列中的每個值(從左到右)開始縮減,最終計算為一個值;
  • reduce()可以作為一個高階函式,用於函式的 compose;
  • 注意reduce()對於空陣列是不會執行回撥函式的。

語法:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue

)

  • 引數:
total 必需。初始值,或者計算結束後的返回值。
currentValue 必需。當前元素。
currentIndex 可選。當前元素索引
arr 可選。當前元素所屬的陣列物件
initialValue 可選。傳遞給函式的初始值

實現程式碼:(過濾陣列物件中的重複元素)

const filterArray = (array) => {
	let tmp = {};
	let tmpArray = array.reduce((total, item) => {
		tmp[item.id] ? '' : (tmp[item.id] = total.push(item));
		return total
	}, []);
	return tmpArray;
}

例項使用:

// 使用
let testArray = [{
	id: 1,
	name: 'zhangsan'
}, {
	id,
	2,
	name: 'lisi'
}, {
	id: 1,
	'zhangsan'
}, {
	id: 4,
	name: 'wangwu'
}];
// 過濾後資料
let newArray = filterArray(testArray);

newArray = [{
	id: 1,
	name: 'zhangsan'
}, {
	id,
	2,
	name: 'lisi'
}, {
	id: 4,
	name: 'wangwu'
}];