Question:
Write a function add that adds an element to the end of an array. However, the element should only be added if it is not already in the array.
Example: add([1, 2], 3) should return [1, 2, 3] and add([1, 2], 2) should return [1, 2].
Answer:
function add (arr, e) {
if (arr.indexOf(e) === -1) {
arr.push(e);
return arr;
} else {
return arr;
}
};
> declare a function add
> it has 2 parameters arr & e
> we need to first check if 'e' is already present in the array - arr
> if it is present then it will not be added to the array - arr
> if it is not present then it will be added to the array - arr
> so after we declare the function, we will open an if / else statement
> the condition will be to check if the indexOf method on the array contains the 'e' element
> if it returns the -1 or is equal to -1, then we shall add that element using the push method
> or else we shall just return the original array
No comments:
Post a Comment