Photo by Hacker Noon on Unsplash

Daily Hack in JavaScript find Index and Value of an object | Day-1

Deepak Vishwakarma
4 min readDec 1, 2019

--

According to Wikipedia, JavaScript is a high-level, just-in-time compiled, object-oriented programming language that conforms to the ECMAScript specification.

However, JavaScript is more than that. Let’s explore valueOf and indexOf

indexOf: The indexOf() a method returns the first index at which a given element can be found in the array, or -1 if it is not present.

let data = [1,2,3,4,1,2, 1]console.log(`index of indexOf 1: `+data.indexOf(1)) // index of indexOf 1: 0console.log(`index of indexOf 1: `+data.indexOf(1, 3)) // index of indexOf 1: 4

The above example is simple. An array of any primitive data returns the position of the element in the array. Let’s see the basic implementation of indexOf.

Array.prototype.indexOf = (function (Object, max, min) {
"use strict";
return function indexOf(member, fromIndex) {
if (this === null || this === undefined)
throw TypeError("Array.prototype.indexOf called on null or undefined");
var that = Object(this),
Len = that.length >>> 0,
i = min(fromIndex | 0, Len);
if (i < 0) i = max(0, Len + i);
else if (i >= Len) return -1;
if (member === void 0) {
// undefined
for (; i !== Len; ++i) if (that[i] === void 0 && i in that) return i;
} else if (member !== member) {
// NaN
return -1; // Since NaN !== NaN, it will never be found. Fast-path it.
} // all else
else for (; i !== Len; ++i) if (that[i] === member) return i;
// if the value was not found, then return -1
return -1;
};
})(Object, Math.max, Math.min);

Things to be noticed if you try to get the index in a null or undefined. It will throw TypeError. Another thing to be noticed, === Strict Equal. This is matching data strictly.

indexOf works perfectly in an array of primitive data(JS defined objects). However, this will not work for an array of objects (Dev defined objects).

Number(1) === Number(1) // true

{name: “deepak”} === {name: “deepak”} // false

class User{
constructor(name){
this.name = name
}
}
new User("deepak") === new User("deepak") // false

So how to find the index of the object in an array? You can use find and findIndex API to get the object.

let data = [
{name: "deepak"},
{name: "SC"},
{name: "zhao"},
{name: "SC"}
]
console.log(`index of indexOf: `+ data.indexOf({name: "SC"}))
// index of indexOf: -1
console.log(`index of findIndex: `+ data.findIndex( user => user.name == "SC"))
// index of findIndex: 1

You can create a find callback function as a reusable method using curry function.

class User{
constructor(name){
this.name = name
}
}
User.matchByName = (name) => user => user.name == namelet user = [
new User("deepak"),
new User("SC"),
new User("zhao"),
new User("SC")
]
console.log(`index of findIndex using curry: `+ user.findIndex(User.matchByName("SC")))
// index of findIndex using curry: 1

Now let’s explore valueOf

valueOf: The valueOf the method returns the primitive value of the specified object.

Number(1).valueOf() // 1

By default valueOf return object proto in return.

let user = {name: “deepak”}user.valueOf() 
// {name: “deepak”} name: “deepak”__proto__: Object

We can simplify the find, using monkey patching or adding new function to Array.prototype.

class User{
constructor(name){
this.name = name
}
}
User.prototype.valueOf = function() {
return this.name
}
new User("deepak").valueOf() // "deepak"
// Override valueOfclass User{
constructor(firstName, lastName){
this.firstName = firstName
this.lastName = lastName
}
}
User.prototype.valueOf = function() {
return `${this.firstName} ${this.lastName}`
}
new User("deepak", "sharma").valueOf() // "deepak sharma"

Benefit of overriding valueOf, we can overload the behaviour of the + operator.

const deepak = new User("Deepak", "Shrama")
"Mr. " + deepak // "Mr. Deepak Shrama"

Let’s see the custom findIndex for object function.

class User{
constructor(firstName, lastName){
this.firstName = firstName
this.lastName = lastName
}
}
User.prototype.valueOf = function() {
return `${this.firstName} ${this.lastName}`
}
let user = [
new User("deepak"),
new User("SC"),
new User("zhao"),
new User("SC")
]
const otherObject = new User("SC")console.log(`index of otherObject: `+ data.indexOf(otherObject))
// index of otherObject: -1
Array.prototype.findObjectIndex = function (data) {
const index = this.indexOf(data)
if(index !== -1) return index
else return this.findIndex(x => x.valueOf() === data.valueOf())
}

Here findObjectIndex can be used on any Array.

console.log(`index of otherObject: `+ users.findObjectIndex(otherObject))
// index of otherObject: 1

For more useful methods, Please have a look at Global_Objects/Array

Note: Overriding or adding prototype method is not recommended. This article is only to understand the core concept of JavaScripts.

This is one of the articles, contains the core concept of JavaScript. If you like this article or my other article, please support me by subscribing and clapping for me.

--

--

Deepak Vishwakarma

I am a polyglot Blockchain Developer. Mainly work on JavaScript and Nodejs. I work for a multinational Bank as Tech Lead to define the best architecture.