[英]Removing duplicates from two arrays in javascript based on a single attribute
我在 javascript 中有兩個 arrays,我想做兩個不同的操作
到目前為止我有這個 function
export function generateDisplayedLabels(systemLabels, masterState){
const mappedSystemlabels = systemLabels.map(label => Object.assign(label, {type: "system"}))
const mappedMasterlabels = masterState.map(label => Object.assign(label, {type: "master"}))
const displayedLabels = _.union(mappedSystemlabels, mappedMasterState);
return displayedLabels
}
這將起作用,除了以下事實,即每當我在開始時對對象進行 map 時,“唯一”元素不再是唯一的,因為它們有另一個屬性映射在其上。 是否有一種省時的方法,我可以過濾掉已映射到其上的非唯一元素,而忽略屬性。
let ar1 = [ { id: 1, name: 'stack', }, { id: 2, name: 'react', }, ]; let ar2 = [ { id: 1, name: 'javascript', }, { id: 2, name: 'overflow', }, { id: 2, name: 'react', }, ]; console.log(_.unionBy(ar1, ar2, 'id')); console.log("======"); console.log(_.unionBy(ar1, ar2, 'name'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.