Menu

gitpiper

haveSameContents javascript Code Snippet in 2024

arrayintermediate

Last Updated: 13 July 2024

Checks if two arrays contain the same elements regardless of order.

  • Use a for...of loop over a Set created from the values of both arrays.
  • Use Array.prototype.filter() to compare the amount of occurrences of each distinct value in both arrays.
  • Return false if the counts do not match for any element, true otherwise.
const haveSameContents = (a, b) => { for (const v of new Set([...a, ...b])) if (a.filter(e => e === v).length !== b.filter(e => e === v).length) return false; return true; };
haveSameContents([1, 2, 4], [2, 4, 1]); // true

javascript snippet similar to haveSameContents For You in July 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️