SwitchUp SwitchUp Ranked Best Coding Bootcamps 2025

Diff Two Arrays

Altcademy Team wrote on 7 February 2018

Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.

比较两个数组,然后返回一个新数组,该数组的元素为两个给定数组中所有独有的数组元素。换言之,返回两个数组的差异。

function diff(arr1, arr2) { var newArr = []; // Same, same; but different. return newArr; } diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);

The solution is O(n) by using hashes to keep tracking of item counts. If the item only has 1 count, that means it's unique between the two arrays.
function diff(arr1, arr2) { var newArr = []; var itemsCounter = {}; // get arr1's items into itemsCounter arr1.forEach(function(item) { if (itemsCounter[item] === undefined) { itemsCounter[item] = 1; } else { itemsCounter[item]++; } }); // get arr2's items into itemsCounter arr2.forEach(function(item) { if (itemsCounter[item] === undefined) { itemsCounter[item] = 1; } else { itemsCounter[item]++; } }); Object.keys(itemsCounter).forEach(function(key){ // if the item has only been counted once, that means that item is unique between arr1 and arr2 if (itemsCounter[key] === 1) { newArr.push(key) } }); return newArr; } diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);

Trusted by

Students and instructors from world-class organizations

Imperial College London
Carnegie Mellon University
City University of Hong Kong
Hack Reactor
Cisco Meraki
University of Oxford
Swift
Bazaarvoice
Waterloo
Uber
AtlanTech
Tumblr
Boston College
Bombardier Aerospace
University of St. Andrews
New York University
Minerva Schools at KGI
Merrill Lynch
Riot Games
JP Morgan
Morgan Stanley
Advanced Placement®
Google
KPMG
The University of Hong Kong
University of Toronto
SCMP
Moat
Zynga
Hello Toby
Deloitte
Goldman Sachs
Yahoo
HSBC
General Assembly
Tesla
McGill University
Microsoft

Join the upcoming Cohort #97

Enroll for January 6th, 2025