0

I have an array say

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

I am using javascript indexof() to check if an element exist or not in the array and if it doesn't exits to do something....

my problem is that when an element like, 1,2,3,4,5,6 doesn't exist in the array, it still judge elements like 10 for 1, 12 for 2, 13 for 3, 14 for 4, 15 for 5, 16 for 6. and so it will still return that the element exists eventhough it is not there

eg:

if x = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

this will still not work as it will see 10 as 1

if(data1.indexOf(1)===-1){											document.getElementById("s1").style.backgroundColor= "red";
    $("input[name='seat1']").attr("disabled", "disabled");
}

4
  • 1
    are you talking about strings or arrays? Commented Oct 17, 2016 at 11:18
  • Do you also get x.indexOf('[') == 0? Commented Oct 17, 2016 at 11:22
  • is an array of integers Commented Oct 17, 2016 at 11:27
  • then your question makes no sense, because 1 does not match 10. please add the content of data1 and/or x. Commented Oct 17, 2016 at 11:29

4 Answers 4

1

You could parse the string and use indexOf as array method.

JSON.parse(data1).indexOf(1) ...
Sign up to request clarification or add additional context in comments.

4 Comments

Scholz, I Just did this
var Vals = JSON.parse(data1); if(Vals.indexOf(1)===-1){ document.getElementById("s1").style.backgroundColor= "red"; $("input[name='seat1']").attr("disabled", "disabled"); }
please perform console.log(typeof data1); in the code. what do you read at the console?
Are you sure it is an array? For x = [10], x.indexOf(1) is not returning 0 for me, however if x = "10" then x.indexOf(1) is returning 0.
0

Array.indexOf works in any browser > IE8: MDN Browser compatibility

Polyfill It if you need to support anything.

// POLYFILL TO SUPPORT ANY BROWSER
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {

    var k;

    // 1. Let o be the result of calling ToObject passing
    //    the this value as the argument.
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }

    var o = Object(this);

    // 2. Let lenValue be the result of calling the Get
    //    internal method of o with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = o.length >>> 0;

    // 4. If len is 0, return -1.
    if (len === 0) {
      return -1;
    }

    // 5. If argument fromIndex was passed let n be
    //    ToInteger(fromIndex); else let n be 0.
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }

    // 6. If n >= len, return -1.
    if (n >= len) {
      return -1;
    }

    // 7. If n >= 0, then Let k be n.
    // 8. Else, n<0, Let k be len - abs(n).
    //    If k is less than 0, then let k be 0.
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    // 9. Repeat, while k < len
    while (k < len) {
      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the
      //    HasProperty internal method of o with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      //    i.  Let elementK be the result of calling the Get
      //        internal method of o with the argument ToString(k).
      //   ii.  Let same be the result of applying the
      //        Strict Equality Comparison Algorithm to
      //        searchElement and elementK.
      //  iii.  If same is true, return k.
      if (k in o && o[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}

// TEST ARRAY
var arr = [0,1,2,3,4,6,7,8,9,10,12,13,14,16,17,18,20]
// TESTS
var offset = 0;
for(var i = 0; i <= 20; i++) {
  if(arr.indexOf(i) === -1) {
    console.log(i, "not found");
  } else  {
    console.log(i, "found")
  }
}

Comments

0

Your example snippet is not helpful, as it does not show the data ("data1") you are working on.

The behaviour you describe is not the one which one gets with your example array:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];

alert("indexOf(1):" + x.indexOf(1));
alert("indexOf(10):" + x.indexOf(10));
alert("indexOf(0):" + x.indexOf(0));

It works as intended.

Your real data proably contains strings and not integers.

1 Comment

ur solution works for ur case but i don't know why is not working for me, the elements of my array are integers not stings
0

I would convert them to strings like this.

function existsInArray(numberArrays, number){
       const numAsStrings = numberArrays.join(',').split(',')
       return numAsStrings.indexOf(String(number)) > -1
    }
    
    console.log(existsInArray([1,2,3,4,5,6,33], 33))
    //true
    
    console.log(existsInArray([1,2,3,4,5,6,33], 34))
    //false

Hope this helps.

2 Comments

the data1 is a json return data
Shouldnt matter as long as you pass an array into the function (and ofcourse the items are just numbers like you showed in your example)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.