“JS -Array -Intersektionsobjekt” Code-Antworten

JavaScript do Arrays kreuzen sich

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

JS -Array -Intersektionsobjekt

const arr1 = [{ id: 1 }, { id: 2 }]
const arr2 = [{ id: 1 }, { id: 3 }]
const intersection = arr1.filter(item1 => arr2.some(item2 => item1.id === item2.id))
// intersection => [{ id: 1 }]
foloinfo

Suchen Sie den Schnittpunkt zwischen zwei Objektarrays 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

Array Intersection JavaScript ES6

const intersection = (a, b) => {
  b = new Set(b); // recycling variable
  return [...new Set(a)].filter(e => b.has(e));
};

console.log(intersection([1, 2, 3, 1, 1], [1, 2, 4])); // Array [ 1, 2 ]
Charming Cheetah

Ähnliche Antworten wie “JS -Array -Intersektionsobjekt”

Fragen ähnlich wie “JS -Array -Intersektionsobjekt”

Weitere verwandte Antworten zu “JS -Array -Intersektionsobjekt” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen