Ad

Does Array.prototype.indexOf() Work Different In React.js

Im trying to understand how this code works I am using Array.prototype.indexOf() to to get the index of the state array so it can be updated. I am told to pass an object in the parameters of indexOf() but i thought that no two objects are equal so how can indexOf() return the right index am i missing something here? here is my code

 handleIncrement(counter){//passing object here from child component

         const counters = [...this.state.counters];//cloning
         const index = counters.indexOf(counter)//geting index of param counter 
         console.log(counter === index)//how did index return true if this returns false???
        counters[index] = {...counter};// spread object onto index pos

        counters[index].value++;//increment value
        this.setState({counters})//updates state just fine no errors
     }
Ad

Answer

You're misinterpreting .indexOf(). indexOf returns the first index at which a given element can be found in the array, or -1 if it is not present. So index would be the index of the counter in counters. In short, you're comparing an object (counter) to a number (index).

That said, it also depends on how you're searching for the object in the array. If trying to find an object which matches a certain key/value structure, .indexOf won't work for the reason you mentioned. As pointed out by Gabriele, if searching using a reference, it will work.

If using a reference isn't an option, as an alternative you could use .findIndex(), or .map(), and find the object based on one of its properties, like id.

const counters = [{id: 1, value: 0}, {id: 2, value: 0}, {id: 3, value: 0}, {id: 4, value: 0}];

const findBySameness = {id: 3, value: 0};
const findByRef = counters[2];

const indexBySameness = counters.indexOf(findBySameness);
console.log('Index by sameness: ', indexBySameness); // Do not find the object index
const indexByRef = counters.indexOf(findByRef);
console.log('Index by reference: ', indexByRef); // Found the object index

// If a reference to the object is not available you can use the following methods

// With .findIndex
const index3 = counters.findIndex(item => item.id === findBySameness.id)
console.log('Index: ', index3); // Found the object index

// With .map
const index2 = counters.map(item => item.id).indexOf(findBySameness.id);
console.log('Index: ', index2); // Found the object index

Ad
source: stackoverflow.com
Ad