1

I have an array in javascript. I've been trying to search the index but it is very frustrating. There is an object inside an array, and inside the object have an array as a value.

This is what the source code looks like:

rows = [{"id":"id0","cell":["array1","array2"]},{"id":"id1","cell":["array3","array4"]}];

I've tried this:

var v = {cell:["array1","array2"]};
rows.indexOf(v)

And also have a radio button:

<input type="radio" name='array' value="array1, array2">

jQuery here:

var i = $("input:checked").val().split(',');
rows.indexOf(i)

which has an index result of -1

Victor
  • 3,669
  • 3
  • 37
  • 42
faddi
  • 71
  • 1
  • 10

1 Answers1

3

Try this. It's a functional approach that loops through each index in rows, and returns true if there's a match.

var rows = [{"id":"id0","cell":["array1","array2"]},{"id":"id1","cell":["array3","array4"]}];
var index = rows.findIndex(function(i) {
  return JSON.stringify(i.cell) == JSON.stringify(["array1","array2"])
});
console.log(index);

The output should return 0. The reason we need to convert both objects into JSON.strings is because of how javascripts handles the equality of two objects. You can read more about it here.

Joseph Cho
  • 4,033
  • 4
  • 26
  • 33