“JavaScript mendapatkan persimpangan dua array” Kode Jawaban

JavaScript melakukan array berpotongan

let intersection = arrA.filter(x => arrB.includes(x));
Eager Echidna

JavaScript mendapatkan persimpangan dua array

function getArraysIntersection(a1,a2){
    return  a1.filter(function(n) { return a2.indexOf(n) !== -1;});
}
var colors1 = ["red","blue","green"];
var colors2 = ["red","yellow","blue"];
var intersectingColors=getArraysIntersection(colors1, colors2); //["red", "blue"]

Grepper

Temukan persimpangan antara dua array objek JavaScript

// Generic helper function that can be used for the three operations:        
const operation = (list1, list2, isUnion = false) =>
    list1.filter(
        (set => a => isUnion === set.has(a.userId))(new Set(list2.map(b => b.userId)))
    );

// Following functions are to be used:
const inBoth = (list1, list2) => operation(list1, list2, true),
      inFirstOnly = operation,
      inSecondOnly = (list1, list2) => inFirstOnly(list2, list1);

// Sample data
const list1 = [
    { userId: 1234, userName: 'XYZ'  }, 
    { userId: 1235, userName: 'ABC'  }, 
    { userId: 1236, userName: 'IJKL' },
    { userId: 1237, userName: 'WXYZ' }, 
    { userId: 1238, userName: 'LMNO' }
];
const list2 = [
    { userId: 1235, userName: 'ABC'  },  
    { userId: 1236, userName: 'IJKL' },
    { userId: 1252, userName: 'AAAA' }
];
  
console.log('inBoth:', inBoth(list1, list2)); 
console.log('inFirstOnly:', inFirstOnly(list1, list2)); 
console.log('inSecondOnly:', inSecondOnly(list1, list2));
Combative Cheetah

Jawaban yang mirip dengan “JavaScript mendapatkan persimpangan dua array”

Pertanyaan yang mirip dengan “JavaScript mendapatkan persimpangan dua array”

Lebih banyak jawaban terkait untuk “JavaScript mendapatkan persimpangan dua array” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya