I have an array of elements of the same class, how can I search indexOf with only one element from the class
class Dhash {
constructor(Dlable, tophash) {
this.Dlable = Dlable;
this.tophash = tophash;
}
}
let listohashs = [];
listohashs[0] = new Dhash(0x001003, 0xfffffffffffffffffffffffffffffffffa);
listohashs[1] = new Dhash(0x011003, 0xfffffffffffffffffffffffffffffffffb);
listohashs[2] = new Dhash(0x021003, 0xfffffffffffffffffffffffffffffffffc);
console.log(listohashs.indexOf(0x001003)); // <-- here be the problem
I need it to return 0 for this example as it matches listohashs[0].dlable
that way i can get the corosponding tophash
value
I have tried:
console.log(listohashs.indexOf(0x001003));
and putting .dlable
anywhere in there that I could think of.
can I search with a wild card in one of the element places? i.e. where * will match anything
searchohash = new Dhash(0x001003, *);
console.log(listohashs.indexOf(searchohash));
Is json what i should be using? im new to js and just started using json a few days ago
CodePudding user response:
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. - MDN
You are looking for the element whose value if 0x001003
but listohashs
is an array of objects. So you are comparing the object with 0x001003
which won't be equal so it will return -1
.
You can use findindex
here, You have to find the index
of the object whose Dlable
property value is 0x001003
class Dhash {
constructor(Dlable, tophash) {
this.Dlable = Dlable;
this.tophash = tophash;
}
}
let listohashs = [];
listohashs[0] = new Dhash(0x001003, 0xfffffffffffffffffffffffffffffffffa);
listohashs[1] = new Dhash(0x011003, 0xfffffffffffffffffffffffffffffffffb);
listohashs[2] = new Dhash(0x021003, 0xfffffffffffffffffffffffffffffffffc);
console.log(listohashs.findIndex((o) => o.Dlable === 0x001003)); // <-- here be the problem
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
indexOf
only works if the argument is an actual element of the array, not just a property of it.
Use findIndex()
to find an element using a function that will perform the appropriate comparison.
class Dhash {
constructor(Dlable, tophash) {
this.Dlable = Dlable;
this.tophash = tophash;
}
}
let listohashs = [];
listohashs[0] = new Dhash(0x001003, 0xfffffffffffffffffffffffffffffffffa);
listohashs[1] = new Dhash(0x011003, 0xfffffffffffffffffffffffffffffffffb);
listohashs[2] = new Dhash(0x021003, 0xfffffffffffffffffffffffffffffffffc);
console.log(listohashs.findIndex(h => h.Dlable == 0x001003));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>