0

I am trying to solve a challenge from jshero.net.

The challenge is:

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. add([1, 2], 3) should return [1, 2, 3] and add([1, 2], 2) should return [1, 2].

The problem is for Array:indexOf(). Does anyone know how to solve it?

Melchia
  • 22,578
  • 22
  • 103
  • 117
  • have you read [`Array#indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) or better [`Array#includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)? – Nina Scholz Jun 16 '20 at 17:14
  • 1. Flatten the inner array (flat at any depth .eg shown below with depth 4). function add(array, number) { const flattendArray = array.flat(Infinity); flattendArray.push(number); return [...new Set(flattendArray)] } console.log(add([1, 2, [3, 4, [4, 6, [7, 8, [8, 9, 10]]]]], 11)); – khizer Jun 16 '20 at 17:36

1 Answers1

0

You can try using Array.prototype.includes to check if the number exists in the array

function add(arr, number) {
  if (arr.includes(number)) return arr;
  else return [...arr, number];

}

console.log(add([1,2], 3));
console.log(add([1,2], 2));

You can also use Array.prototype.indexOf:

function add(arr, number) {
  if (arr.indexOf(number) > -1) return arr;
  else return [...arr, number];

}

console.log(add([1,2], 3));
console.log(add([1,2], 2));
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Melchia
  • 22,578
  • 22
  • 103
  • 117
  • 1
    IT WORKED . Thank you very much. It ran perfectly. – DefNotBruceWayne Jun 16 '20 at 17:19
  • @DefNotBruceWayne Alternatively, you can call `arr.indexOf(number) !== -1`, if you wanted another way to do this. This is the more language-agnostic approach, the one most people unfamiliar with JS would go with. – Mr. Polywhirl Jun 16 '20 at 17:20
  • @Melchia , what downvote? I never downvoted anything – DefNotBruceWayne Jun 16 '20 at 17:25
  • @Melchia this solution won't work if you have depth of inner array more than 1. Thanks but great work!! – khizer Jun 16 '20 at 17:38
  • @khizer Where is it stated in the question that we're dealing with multi layer arrays ? – Melchia Jun 16 '20 at 17:39
  • @Melchia It isn't stated but solution should be generic IMO. Just a good way :) plus what will be the solution in case of console.log(add([2,2], 2)); => it should be [2] only ;) – khizer Jun 16 '20 at 17:42
  • How do you know that we're not trying to preserve the original array? If the question was just to remove duplicates from the array we would've used Set directly! just stick to the question! – Melchia Jun 16 '20 at 17:44
  • This question is clearly a duplicate, so it should be simply marked as one, instead of repeating such a basic answer :) – matvs Jun 19 '20 at 13:27