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

1
  • @ObsidianAge yes i use split() to make the value an array Commented Oct 19, 2017 at 20:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

do keep in mind though the if the array was ["array2","array1"] it would not match.
how to call elemen of array cell foreach statement?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.