DEV Community

Cover image for One liner operations on Arrays
Akhil sai
Akhil sai

Posted on

2 2

One liner operations on Arrays

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay