+ 5
Problem with arrays in Javascript[solved]
I expected to see Index 0 here https://code.sololearn.com/WVx9HLRo7YM5/#js What must I do?
13 odpowiedzi
+ 7
I didn't find any solution, but I invented one, maybe it will help you. It works only with two-dimensional arrays, but you can edit it to work with any length:
/*
* @author Luis Calderon
* @description find two-dimensional arrays
* @param { Array } toFind value to find
* @return { number } Index of the found array, if not it returns -1
*/
Array.prototype.findArray = function (toFind) {
var onIndex = -1;
this.find((value, index) => {
var exist = (value[0] === toFind[0]) && (value[1] === toFind[1]);
if (exist) onIndex = index;
});
return onIndex;
}
a = [[2, 5], [1, 3], [20, 3], [0, 0], [2, 4], [1, 1], [1, 4]];
//tests
console.log(a.findArray([0, 1]));//-1
console.log(a.findArray([1, 3]));//1
console.log(a.findArray([2, 4]));//4
console.log(a.findArray([2, 5]));//0
console.log(a.findArray([0, 1]));//-1
try it:
https://code.sololearn.com/WqccsU3U2sgn/?ref=app
+ 7
indexOf uses strict equality === and in JavaScript arrays are objects. So different but similar arrays are not equal.
When using the same array instance, it works
https://code.sololearn.com/Wp22bIIG20ES
+ 7
grrrrrrrr
I want my python back😱😱😱
+ 7
If the problem has been solved add "Solved" in your question heading.😊
+ 5
Oma Falk you may have to create your own function that does that. 😉
+ 5
Lol. Check if lodash or underscore can help with that.
+ 4
luis calderón
finally I did it similiar
https://code.sololearn.com/WyShFT4q6l7z/?ref=app
+ 4
HonFu
indexOf will always result in - 1
Javascript tests for ===
means identity not equality.
That exactly was my prob.
+ 2
Ore I save coordinates in my Array. I need a solution to see, if coords already in my array.
What can I do?
+ 2
Isn't that just a reference issue, just like in Python?
EDIT: Seems it is.
If you create the list first, it is found properly.
var a = []
var b = [1,2]
a.push(b)
alert(a)
alert(a.indexOf(b))
if (a.indexOf([1,2]) >= 0){
alert("Array found")
}}
+ 2
Yeah, Python IS convenient, isn't it?
You have 'is' and ==, so you can ducktype your array-like objects so that they give True for comparable content AND preserve the identity of each container anyway.
+ 1
It is tricky.
Even stuff that looks exactly the same, may behave differently between the languages.
Operator precedence being one of them. You basically have to make sure every time, when things become a little more complex.