0

I have this data

    var selectedValue = [];
    selectedValue.push({0:'Data A'});
    selectedValue.push({1:'Data B'});

I want to check if my new data is already exists in that array. I'm trying to use includes()

function inArrayCheck(val) {
  console.log(selectedValue.includes(val));
}

Then i try another way

function inArrayCheck(val) {
    if (Object.values(selectedValue).indexOf(val) > -1) {
   console.log(val);
    }
}

both of them returning false when i input Data A

Boby
  • 1,131
  • 3
  • 20
  • 52
  • What is `selectedValue` here? – palaѕн Feb 22 '20 at 16:59
  • 1
    Why are you wrapping the values in objects? Why not just `selectedValue.push('Data A')`? – Barmar Feb 22 '20 at 17:02
  • 1
    If you have an array of objects, you should use the same property names in all the objects, not different properties. E.g. `selectedValue.push({key: 0, value: "Data A"})` – Barmar Feb 22 '20 at 17:02
  • Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – Mahatmasamatman Feb 22 '20 at 17:10

3 Answers3

2

Objects will not be equal unless they have the same reference, even when they have the same key/value pairs. You can do the comparison after converting the objects to string using JSON.stringify with limited capability, like the order of elements in the object and the case of strings matters:

var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});


function inArrayCheck(val) {
  return selectedValue.some(obj => JSON.stringify(obj) === JSON.stringify(val))
}

console.log(inArrayCheck({0:'Data A'}))
Addis
  • 2,480
  • 2
  • 13
  • 21
0

You are trying to find a value from an object which is inside an array. You can try like so:

var selectedValue = []; // this is an array
selectedValue.push({0:'Data A'}); // here you push an object to the array
selectedValue.push({1:'Data B'}); // to find the value later you need to find it inside the object!
// above three lines can also be written like so and are the same
// var selectedvalue1 = [{0:'Data A'}, {1:'Data B'}];

function inArrayCheck(val) {
  selectedValue.forEach(function(element){
    if (Object.values(element).indexOf(val) > -1) {
        console.log('found value: ' + val);
    }
  });
}

inArrayCheck('Data A');

if you want to use includes you need to have an array like so:

var selectedValue = [];
selectedValue.push('Data A');
selectedValue.push('Data B');
// above three lines can also be written like so and are the same
// var selectedvalue1 = ['Data A', 'Data B'];

function inArrayCheck(val) {
  console.log(selectedValue.includes(val));
}

inArrayCheck('Data A')
caramba
  • 21,963
  • 19
  • 86
  • 127
-1

You forgot to go trough each value. You can also use find() function, to check if array have a value which sutisfy your condition.