0

I have a simple array with a few elems & a new elem , trying to check the elems with a function , push the new elem into the array if not already present & ignore it if it is.

I created a function with an if /else statement but the code always adds the new item to the array.

var arr=['a','b'];
var newElem='c';
function f(){
   for(var i=0; i<arr.length; i++){
     if(arr[i] == newElem){ console.log('Exists');return }
     else {arr.push(newElem);console.log(arr); return }
   }
}
f();

The code works fine if the new item not present in the array but if it's ,the new elem still being pushed into the array? Pls anyone could help , don't want to ask the teacher , it looks so simple ?

  • If you have a teacher, and most probably you also pay for it, ask him :) no shame – quirimmo Jan 07 '19 at 09:28
  • not able to reproduce the error – brk Jan 07 '19 at 09:31
  • @brk Issue is, OP is checking in loop. So if you try to push an element that exists at say 2nd index, for first iteration, `(arr[i] == newElem` will fail and value will be pushed in array – Rajesh Jan 07 '19 at 09:33
  • Considering your logic, the small mistake you have done is that you are not looping through all the elements before pushing: `var arr=['a','b']; var newElem='c'; function f(){ var flag = false; for(var i=0; i – Pavan Skipo Jan 07 '19 at 09:42
  • Thnks pavan for pointing out the flaw in the data flow. – J.Zemplyn Jan 09 '19 at 08:41
  • I've run it in an html file & if the (return) is not within the first if-curly-brackets it doesn't seem to work properly while in a console.log environment it works both ways? – J.Zemplyn Jan 09 '19 at 08:48
  • quirimmo! We have a school break here Down-under currently. – J.Zemplyn Jan 09 '19 at 08:56

1 Answers1

0

Check if element exists first like so:

const arr = ['a', 'b'];
const newElem = 'c';
if (arr.indexOf(newElem) === -1) {
  arr.push(newElem);
}
Melas
  • 26
  • 2