+ 5

Problem with arrays in Javascript[solved]

I expected to see Index 0 here https://code.sololearn.com/WVx9HLRo7YM5/#js What must I do?

9th Aug 2020, 2:12 PM
Oma Falk
Oma Falk - avatar
12 Respostas
+ 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
9th Aug 2020, 4:02 PM
CoffeeByte
CoffeeByte - avatar
+ 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
9th Aug 2020, 2:43 PM
Ore
Ore - avatar
+ 7
grrrrrrrr I want my python backđŸ˜±đŸ˜±đŸ˜±
9th Aug 2020, 2:56 PM
Oma Falk
Oma Falk - avatar
+ 7
If the problem has been solved add "Solved" in your question heading.😊
11th Aug 2020, 7:46 AM
Sakshi💕
Sakshi💕 - avatar
+ 5
Oma Falk you may have to create your own function that does that. 😉
9th Aug 2020, 2:52 PM
Ore
Ore - avatar
+ 5
Lol. Check if lodash or underscore can help with that.
9th Aug 2020, 2:59 PM
Ore
Ore - avatar
9th Aug 2020, 7:50 PM
Oma Falk
Oma Falk - avatar
+ 4
HonFu indexOf will always result in - 1 Javascript tests for === means identity not equality. That exactly was my prob.
11th Aug 2020, 8:44 AM
Oma Falk
Oma Falk - avatar
+ 2
Ore I save coordinates in my Array. I need a solution to see, if coords already in my array. What can I do?
9th Aug 2020, 2:49 PM
Oma Falk
Oma Falk - avatar
+ 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") }}
11th Aug 2020, 8:11 AM
HonFu
HonFu - avatar
+ 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.
11th Aug 2020, 8:50 AM
HonFu
HonFu - avatar
+ 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.
11th Aug 2020, 9:13 AM
HonFu
HonFu - avatar