Well first of all I want to comment that I have a data structure as follows:
arrayJson = [{"point":[5,4]},{"point":[2,2]},{"point":[1,6]},
{"point": [8,9]} ]
The objective is to find the index within the array that meets a condition and that is that "point" is equal to a certain value, I have tried to do it in the following way:
function encontrarElemento(element) {
return element.point == [5,4];
}
console.log(array1.findIndex(encontrarElemento));
I don't know why, but the console output tells me it's -1, which means it's not finding the element.
You had formatting errors in the JSON you posted. Once solved I thought about this solution.
The first thing I did was set up a loop to iterate through the JSON elements . Since there is no direct comparison method
arrays
(that I know of), what I came up with is to transform them into JSON format so that I can compare them and thus return the element you need.EDIT
The code above would return the element that matches the search pattern. If what you need is to return the position of
array
where it is, you could use something like this:Let's go by parts:
The comparison between Arrays is not the same as a comparison between other types in JavaScript, if you compare it
1 === 1
will betrue
, but if you compare[1] === [1]
the result isfalse
. That's why yourfindElemento()
doesn't work as expected.One idea I've come up with to approximate it is to reduce the values to booleans first, and then find the index of true:
See if this works for you
Converting to json for comparison is more expensive and poorly understood than comparing the actual data.
Using map, reduce and indexOf is hard to read.
The comparison of objects, and arrays are objects, should not be done with
==
because there you are comparing if it is the same object, not if the value is the same. For example: