DEV Community

loading...
Cover image for One liner operations on Arrays

One liner operations on Arrays

akhil_001 profile image Akhil sai ・1 min read

Introduction

  • This post covers the useful snippets for operations on 2 arrays.
  • An array is considered as a set in mathematical terms throughout this post
  • Assumptions:

    • Arrays are not nested
    • There are 2 arrays named arrA and arrB
    const arrA = [2,4,6,8,10];
    const arrB = [3,6,9,10];
    

Intersection of 2 arrays ( A ∩ B)

const intersectionOfArrays = arrA.filter(el => arrB.indexOf(el) !== -1);
 // [6,10] 

Elements Unique to ArrayA (A-B)

const uniqueToArrA = arrA.filter(el => arrB.indexOf(el) === -1);
// [2,4,8]

Elements Unique to ArrayB (B-A)

const uniqueToArrB = arrB.filter(el => arrA.indexOf(el) === -1);
// [3,9]

XOR of Arrays A and B (A ^ B)

const xorOfAandB = uniqueToArrA.concat(uniqueToArrB);
// [2,4,8,3,9]

Union of Arrays A and B (A U B)

const unionOfAandB = arrA.concat(arrB);
// [ 2, 4, 6, 8, 10, 3, 6, 9, 10 ]

Conclusion

  • There are several libraries out there (eg: Lodash) that do these operations efficiently.
  • But these snippets come in handy when you are working on pet projects that donot generally need the overhead of the libraries

Discussion (0)

pic
Editor guide