diff --git a/removeelement/index.test.js b/removeelement/index.test.js new file mode 100644 index 0000000..e505d32 --- /dev/null +++ b/removeelement/index.test.js @@ -0,0 +1,19 @@ +const { expect } = require("chai") +const removeElement = require("./solution"); + +describe("remove element", () => { + it("should remove an element and return its length", () => { + const result = removeElement([3, 2, 1, 3], 3); + expect(result).to.equal(2); + }); + + it("returns 4 when val is not in an arr below", () => { + const result = removeElement([3, 2, 1, 3], 5); + expect(result).to.equal(4); + }); + + it("should return 0 when arr is empty", () => { + const result = removeElement([], 3); + expect(result).to.equal(0); + }); +}); diff --git a/removeelement/question.txt b/removeelement/question.txt new file mode 100644 index 0000000..a5206fd --- /dev/null +++ b/removeelement/question.txt @@ -0,0 +1,16 @@ +-> Given an array arr and a value val, +-> remove all instances of that value in-place +-> and return the new length. + +-> Do not allocate extra space for another array, +-> you must do this by modifying the input array in-place with O(1) extra memory. + +-> The order of elements can be changed. +-> It doesn't matter what you leave beyond the new length. + +Example:- + +-> Given arr = [3,2,2,3], val = 3, +-> Your function should return length = 2 +-> with the first two elements of arr being 2. +-> It doesn't matter what you leave beyond the returned length. \ No newline at end of file diff --git a/removeelement/solution.js b/removeelement/solution.js new file mode 100644 index 0000000..62e7da3 --- /dev/null +++ b/removeelement/solution.js @@ -0,0 +1,19 @@ +const removeElement = (arr, val) => { + // initialize count to zero + let counts = 0; + // loop through the arra + for (let i = 0; i < arr.length; i++) { + /** + * check if num is not equal to val + * then increment the number of counts + * but assigining its num values + */ + if (arr[i] != val) { + arr[counts++] = arr[i] + } + } + // return our counts + return counts; +} + +exports = module.exports = removeElement;