DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for JavaScript challenges_1 🐲
Mahmoud EL-kariouny
Mahmoud EL-kariouny

Posted on

JavaScript challenges_1 🐲

Array.diff

  • Your goal in this kata is to implement a difference function.
  • Which subtracts one array from another and returns the result.
  • It should remove all values from array [a].
  • Which are present in array [b] keeping their order.

Examples:

  • arrayDiff([1,2],[1]) == [2]

  • If a value is present in b,

  • All of its occurrences must be removed from the other:

  • ArrayDiff([1,2,2,2,3],[2]) == [1,3]

Task URL

My solution:

let arr1 = [1, 2, 2, 2, 3];
let arr2 = [2];

function arrayDiff(a, b) {
    let result = []
    for (let i = 0; i < a.length; i++) {
        if (b.indexOf(a[i]) === -1) {
            result.push(a[i])
        }
    }
    return result;
}
console.log(arrayDiff(arr1, arr2))

// Output
[ 1, 3 ]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!