What is the best way to locate the position of an element within an Array with underscore.js?

I need assistance with finding the index of a specific value within an array using underscore.js.

Here is the scenario I am facing:

var array = [{'id': 1, 'name': 'xxx'},
             {'id': 2, 'name': 'yyy'},
             {'id': 3, 'name': 'zzz'}];

var searchValue = {'id': 1, 'name': 'xxx'};

I have attempted to use the following code:

var index = _.indexOf(array, function(data) { 
                alert(data.toSource()); //For testing purpose 
                return data === searchValue; 
            });

I also tried this alternative approach:

var index = _.indexOf(array, {id: searchValue.id});

Unfortunately, both methods return -1 which indicates that the function was not entered. As a result, the alert message did not appear.

I am seeking help in identifying what is incorrect with my code. Can anyone provide guidance?

Answer №1

If you're looking for a library with handy functions that are missing in underscore, I highly recommend checking out lodash.

Here's an example of how you can use lodash:

var array = [{'id': 1, 'name': 'xxx'},
           {'id': 2, 'name': 'yyy'},
           {'id': 3, 'name': 'zzz'}];

var searchValue = {'id': 1, 'name': 'xxx'};


var index = _.findIndex(array, searchValue); 
console.log(index === 0); //-> true

http://lodash.com/docs#findIndex

If you're sticking with Underscore but want to access lodash's features, you can get lodash's underscore build from


ES2015

With ES2015 being widely used now (thanks to transpilers like Babel), you have the option to skip using lodash and underscore and utilize native methods instead:

var arr = [{ id: 1 }, { id: 2}];

arr.findIndex(i => i.id === 1); // 0

Answer №2

Here is an alternative solution:

let items = [{'id': 1, 'name': 'xxx'},
             {'id': 2, 'name': 'yyy'},
             {'id': 3, 'name': 'zzz'}];

let searchValue = {'id': 1, 'name': 'xxx'};
let index = -1;

_.each(items, function(item, idx) { 
   if (_.isEqual(item, searchValue)) {
      index = idx;
      return;
   }
});

console.log(index); //0

When comparing objects in your code snippet, data === searchValue compares the object references, which may not be what you intend. Using data == searchValue would compare string representations instead. To accurately compare objects, use _.isEqual.

Answer №3

Perhaps my suggestion could offer some valuable insight.

Is there a specific reason you are using callback for the indexOf method? In underscore.js, the signature of indexOf is as follows:

_.indexOf(array, value, [isSorted])

Consider using find for this task instead:

_.find(array, function(item, index) {
  if (item.id === searchValue.id) {
    alert(index);
  }
});

Answer №4

When it comes to objects, the comparison operators === and == are used to determine if two references point to the same object, not necessarily equivalent objects:

var a = {foo: "bar"};
var b = {foo: "bar"};
console.log(a === b); // false, `a` and `b` refer to different (but equivalent) objects
a = b = {something: "here"};
console.log(a === b); // true, `a` and `b` refer to the *same* object

To make a decision about object equality, you need to compare their properties. In this scenario, the id property seems like a good candidate for comparison. Alternatively, if you want to compare all properties, you could utilize Underscore's isEqual method.

Answer №5

When utilizing Underscore, it prioritizes using the native indexOf method if accessible; otherwise, it resorts to a fallback option. Therefore, when dealing with a list of objects, an alternative implementation is necessary.

For instance, consider the following:

_.chain(array).pluck("key").indexOf("value").value();

or

_.map(array,function(e) { return e.key; }).indexOf(value);

Answer №6

If you're dealing with intricate objects and need to search for a specific property within the collection, you can use this simple method:

 _.indexOf(arrayObj, _.findWhere(arrayObj, {key: "value"}));

In this code snippet, "arrayObj" represents the array containing the objects, "key" is the property you are searching for, and "value" is the desired value.

Answer №7

Currently implementing the findIndex method in my code.

 _.findIndex(myArray, valueToSearch); 

Answer №8

_.searchArray(array, function(element, position) {
  if (element.identifier == targetValue.identifier) {
    displayAlert(position);
  }
});

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

Encountering a 'oembed is null' error in the firebug console while using JQUERY OEMBED

There seems to be an issue with oembed causing an error message in firebug's console window. Specifically, the error is displayed as: oembed is null oembedContainer.html(oembed.code); This error occurs when clicking on a link that leads to the jquer ...

The console log displays an unhelpful response even after attaching a then function to it in the chain

While I am attempting to implement a promise in my JavaScript file, I have encountered a peculiar issue. Upon logging the returned value within the function, this is what I see: const id = getAccounts() .then(res => res.find(acc => acc.type === ACC ...

Sublime Text 3 for React.js: Unveiling the Syntax Files

Currently, my code editor of choice is Sublime Text 3. I recently wrote a simple "hello world" example in React, but the syntax highlighting appears to be off. I attempted to resolve this issue by installing the Babel plugin, however, the coloring still re ...

What separates the functions `useRef` and `createRef` from each other?

As I was delving into the hooks documentation, I came across useRef. Upon examining their example… function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // `current` refers to the mounted text inpu ...

How to print a Base64 encoded file with the Print.js library

I am facing an issue with printing a Base64 file. Despite my efforts, the file does not print as expected. function convertToBase64() { var selectedFile = document.getElementById("inputFile").files; if (selectedFile.length > 0) { var fi ...

Switching dropdown orientation of Meteor Accounts

Currently, I have incorporated the following Meteor packages in my project: accounts-ui accounts-password accounts-facebook In order to implement Meteor accounts into my view, I used the code snippet as shown below: <meteor-include src="loginButto ...

Tips for navigating through a webpage by scrolling

My goal is to automatically scroll down to the bottom of the page and then perform a specific action. With the help of uiautomator, I was able to retrieve the following information: index=2, resource-id=com.manoramaonline.arogyam:id/pager,class=android.sup ...

Exploring the Depths of React by Cycling Through Arrays in Tabular Format

One issue I'm facing is that I have an array named paymentMethods which I'd like to iterate through in tabs. However, I seem to be struggling with the iteration part. To take a closer look at my code, please visit my codesandbox HERE <div& ...

What is the best way to concatenate JSON in JavaScript?

How do I merge this JSON data accordingly: complements = ["XYZ 3, CDE TR, AAA 5", "", "NDP 3, DDD FR"] ? Each address may have multiple complements that need to be combined and separated by a comma. Note: JavaScript is bein ...

"Learn how to use JavaScript and jQuery to alphabetically sort the default td values in a table

This table and script are being used to alphabetically sort the data within the td tags: <button type=button>Sort Options</button> <table class="table-data"> <tr> <td class="filename">C</td> </tr> <t ...

Experiencing an unexpected abundance of console logs when implementing React Hooks

I am attempting to retrieve data from an API. The desired result is being obtained, but when I attempt to log it to the console, it logs 4 times. Within my app.js, I am utilizing the fetchData function: import React, {useEffect, useState} from 'rea ...

Ways to present a pop-up dialog box featuring word corrections

I have developed a word correction extension that encloses the incorrect word in a span element. Upon hovering over the word, a drop-down menu with possible corrections should be displayed. However, my current code is not functioning properly. How can I en ...

Synchronization-free API and callback functions

I am in need of utilizing an asynchronous service. My current approach involves sending data to this service using PHP and CURL, as well as receiving data from a URL provided by the service. How can I effectively respond or wait for feedback from this serv ...

Switching to fullscreen mode and eliminating any applied styles

I'm trying to enable fullscreen mode with a button click. I've added some custom styles when the window enters fullscreen, however, the styles remain even after exiting fullscreen using the escape key. The styles only get removed if I press the e ...

Changing the z-index property of a Material-UI <Select> dropdown: What you need to know

Currently, I am implementing an <AppBar> with a significantly high z-index value (using withStyles, it is set to theme.zIndex.modal + 2 which results in 1202). The primary purpose behind this decision is to guarantee that my <Drawer> component ...

Strings that automatically adjust to fit the content from a JSON object

I have a JSON object with a long string that I want to display. The string looks like this: "String":"<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever si ...

AJAX: How to handle a successful POST request?

I have been recently exploring AJAX and I can see why I hesitated to delve into this particular area of JavaScript; it appears quite intricate. Most discussions seem centered around how to SEND data via POST, with little focus on what happens once the POS ...

I seem to be having trouble with the layout alignment in the md-grid-tile

Here is an example I'm working with: http://codepen.io/anon/pen/YqqdYR I am trying to achieve equal spacing between divs nested inside the md-grid-tile. I found guidance on how to do this at: https://material.angularjs.org/latest/layout/alignment, a ...

Incorporate External Web Page Information by Clicking a Button

Apologies if this question has already been asked, but despite my efforts to explore the available resources, I have not found a solution to my issue. I currently have an input field where users can enter their website, keyword, or industry. When they cli ...

Handling typeError in Vue.js JavaScript filter for object manipulation

I need to sort an object based on state names (e.g. Berlin, Bayern ...). Below is the API response I received. "states":{ "Bayern":{ "total":13124737, "rs":"09", "va ...