Finding the index of an element in an array in TypeScript/JavaScript

UPDATE: Despite being labeled as a duplicate, this question showcases @ssube's clever and efficient solution.

UPDATE2: A new method has been suggested by @Grungondola in the comments.

I'm currently working with Typescript.

This first code snippet works like a charm:

var array1 = [];
array1.push(5);
array1.push(6);
console.log("a", array2.indexOf(6));

However, the second snippet encounters an issue. The array2.indexOf returns -1, signifying that the item was not found:

var array2 = [];
array2.push({aa:5,bb:5});
array2.push({aa:6,bb:6});
console.log(array2.indexOf({aa:6,bb:6}));

It appears that indexOf does not support Objects. Are there alternative methods within TypeScript to tackle this problem? Thank you.

Answer №1

It's not a problem with the Object itself, but rather that you're creating distinct objects.

The syntax for object literals ({foo: 'bar'}) creates an object on-the-fly. Each time this syntax is used, a new object is generated, resulting in multiple objects being created.

You can confirm this by comparing {foo: 3} === {foo: 3}. Despite evaluating to false, these are separate objects and not references to the same one.

When utilizing the indexOf method, it searches for a specific object, string, number, etc., within an array. By passing a new object, it won't be found in the array.

If you have a reference to the object, using that will enable indexOf to function correctly:

var foo = {aa:5,bb:5}, bar = {aa:6,bb:6};
var array2 = [];
array2.push(foo);
array2.push(bar);
console.log(array2.indexOf(foo));

This will display the correct index since it's referring to the exact instance.

An alternative approach is to utilize filter or find along with a predicate for deep searching:

function deepIndexOf(arr, obj) {
  return arr.findIndex(function (cur) {
    return Object.keys(obj).every(function (key) {
      return obj[key] === cur[key];
    });
  });
}

var array2 = [];
array2.push(foo);
array2.push(bar);
console.log(deepIndexOf(array2, foo));

This method won't delve into nested objects but serves the purpose of comparing two objects and their immediate fields for equivalence.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to transfer the getJSON output into an input field?

I am attempting to fill out a form with the data from the most recent entry in my database using $.getJSON. Although the GET request successfully returns the JSON, I am struggling to populate the fields with the data. I am relatively new to this and seekin ...

Why is it that a website is loading at a snail's pace on Angular?

Working on my college project has been going smoothly, except for one issue with slow loading times. It's frustrating how long it takes to load. I suspect that there might be an error in the deployment process or something else causing the delay. The ...

Intermittent issue with div background switching feature on Firefox

There's a div where background images are changed using a script. I've simplified everything here: Sometimes, in Firefox, an error occurs about 10% of the time that looks like this: https://i.sstatic.net/JvSfx.png Everything seems to work fine i ...

How can curly braces be utilized in an array reduce method?

If the function `fn3` is used instead of `fn2` in this code snippet running on node 9.5.0, the `console.log(totalUpvotes)` will display `undefined`. Shouldn't it actually be equal to 92? const posts = [{id: 1, upVotes: 2}, {id:2, upVotes: 89}, {id: ...

Display Bootstrap Modal using Typescript in Angular

Looking for some creative ideas here... My Angular site allows users to register for events by filling out a form. They can also register themselves and other people at the same time. https://i.sstatic.net/a44I7.png The current issue ~ when a user clicks ...

How can you utilize data captured through a JavaScript onchange event in conjunction with another event?

Is there a way to utilize the firmType data captured during event 1 in event 2? code event 1 $("body").on("change","#so_customer", function(v){ customerFirm = $(this).find(":selected").data("employer"); $("#customer_employer").val(cust ...

Issue with Kaltura thumbnail video not rendering within a script tag in React, resulting in blank space instead

I have encountered an issue with a Kaltura Thumbnail embed in React. When I use the script tag in a basic HTML page, everything works fine. However, when I try to use the same script tag in React, it only shows an empty space instead of the video. On ins ...

Activate the action using the onclick interaction

window.addEventListener(mousewheelEvent, _.throttle(parallaxScroll, 60), false); My current setup involves an event listener that responds to a mousewheelEvent by executing a function. However, when attempting to directly trigger this function on a separa ...

jQuery mobile enhancing user experience with dynamic background images

I am having trouble setting different background images for each page in jQuery Mobile. <div data-role="page" id="pageone">... </div> <div data-role="page" id="pagetwo">... </div> Since each page has a unique ID, I tried ...

Mastering the art of manipulating the Document Object Model in Vue.js

I have a situation where I am using v-for to display a lot of data in JSON as individual buttons. My goal is to change the background color of the button when it is clicked. I plan to use @click to bind a function to each button, and within that function, ...

Guidelines on specifying the type for a component that is a union type

I came across a situation where I encountered a type error. Here is the case: https://codesandbox.io/s/stupefied-herschel-9lvmb?file=/src/App.tsx import * as React from "react"; import "./styles.css"; const A: React.FC<{ a: string } ...

Converting image bytes to base64 in React Native: A step-by-step guide

When requesting the product image from the backend, I want to show it to the user. The issue is: the API response contains a PNG image if the product has an image, but returns a (204 NO Content) if the product does not have an image. So, I need to display ...

Exploring the properties of individual Vue components on a single page with v-for loop

Struggling to render a Vue component in a Rails app by iterating through an array of data fetched via Ajax. The Slim template (index.html.slim) for the index page includes a custom_form_item component, where items represent custom forms data from Rails and ...

What could be the reason that changing document.body would impact its future accessibility?

This particular block of code functions exactly as anticipated: let vw, vh [vw, vh] = [document.body.clientWidth, document.body.clientHeight] console.log(vw) However, the behavior of this next snippet is not what I expected. It appears that simply havi ...

What is the best way to remove the underline in Material-UI while still keeping the selection feature intact in Autocomplete?

Seeking to develop an Autocomplete feature with the TextField component while eliminating the underline. I successfully disabled the underline by utilizing InputProps={{ disableUnderline: true }} in the TextField properties, however, it also eliminated t ...

Reset input fields while retaining placeholder text

Seeking advice on how to use this handy jQuery tool properly: $('.myDiv input').each(function () { $(this).val(""); }); Though it clears my form, I'm struggling to maintain the placeholders of the inputs. Any suggestions? C ...

Effortless jQuery Parallax

Seeking assistance with debugging this jQuery code that manipulates the top margin of an element within a container. The container has a fixed size and overflow set to hidden to create a parallax effect. The parallax effect is functioning properly, but it ...

Tips on using regular expressions to divide strings based on the pattern of "{{variableValue}}" surrounded by spaces

I'm struggling to create a regex pattern to split strings correctly. Opening line: {{ text1 }} 123 {{text1}}{{text1}} {{ text1}}134 Variable text content: const a = text1; Splitting outcome: ["{{text1}}"," 123 ","{{text1 ...

MySQL Entry Update Failure

This is the HTML/EJS code snippet: <div class="Edit-Panel" style="display: none;"> <div class="Edit-Wrapper"> <div class="Editing"> <p class="Edit-Header ...

Efficiently communicating updates to clients after executing multiple HTTP requests simultaneously in RxJS

Objective: Execute multiple asynchronous HTTP requests simultaneously with RxJS and trigger a callback after each request is completed. For instance: fetchData() { Observable.forkJoin( this.http.get('/somethingOne.json').map((res:Re ...