Skip to content

Instantly share code, notes, and snippets.

@bartcis
Last active August 5, 2019 18:41
Show Gist options
  • Select an option

  • Save bartcis/e97357f0c7fa1592b5807cd1a66dee53 to your computer and use it in GitHub Desktop.

Select an option

Save bartcis/e97357f0c7fa1592b5807cd1a66dee53 to your computer and use it in GitHub Desktop.
Difference between two arrays - solution 2
const arrayOne = [1, 4, 5, 7, 3, 8, 1, 9];
const arrayTwo = [3, 7, 1, 12, 9, 5, 24, 16];
function diffArrayInt(array1, array2) {
// 1. Create new array
const newArr = [];
// 2. Combine the two array and sort
const orderedArr = [...array1, ...array2].sort();
// 3. Loop through the ordered Array
orderedArr.map((item, index) => {
// 4. If given element is not repeated, it's unique
if (item !== orderedArr[index - 1] && item !== orderedArr[index + 1]) {
// 5. Add unique element to the new array
newArr.push(item);
}
});
// 6. Return the array with unique numbers
return newArr;
}
console.time('Start Algo 2');
console.log(diffArrayInt(arrayOne, arrayTwo));
console.timeEnd('Start Algo 2'); // Start Algo 2: 0.527099609375ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment