Finding the index of an array element with multiple sub-elements in JavaScript

Currently, I am focusing on JavaScript and I have the task of finding the index of an element in an array.

const tasks = [{taskno:'1', todo:'cooking'},{taskno:'2', todo:'play'}];

My goal is to locate the index of the task with 'cooking' as its todo value, without knowing its task number. Is there a built-in function for this purpose?

I attempted to use the following code but it did not yield the desired result:

const index = tasks.indexOf({todo: 'cooking'});

Currently, I am resorting to using a for loop for this task. Are there any alternative methods available?

Your assistance is greatly appreciated :)

Answer №1

Finding the index of an object in an array using the indexOf function requires having a reference to that object beforehand.

For example:

var obj1 = { value: 'obj1' },
    obj2 = { value: 'obj2' };

[obj2, obj1].indexOf(obj1); //1

If you do not already have a reference to the object, you will need to implement your own custom search algorithm.

var tasks = [{taskNo:'1', action:'cooking'}, {taskNo:'2',action:'play'}];

var resultIndex = findIndexOfFirstMatch(tasks, function (item) {
    return item.action === 'cooking';
});

console.log(resultIndex); //0

function findIndexOfFirstMatch(array, matcherFunction) {
    var index = 0, length = array.length;

    for (; index < length; index++) {
        if (matcherFunction(array[index])) return index;
    }

    return -1;
}

Answer №2

In order to locate the specific object rather than just its index, you have the option of employing the underscore library along with its findWhere method:

var desired_task = _findWhere(task, {todo: "Cooking"});

If your requirement is to find the index, then you can utilize the task_wanted variable to conduct a search within the array using the indexOf() function.

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

Struggling to capture an error generated by Sequelize within a universal Middleware block

In a test project, I have successfully implemented CLS transaction control in Sequelize using 'cls-hooked'. The transactions work seamlessly both in the command line and with Express. They are injected and managed automatically, rolling back on a ...

Passing a pointer to a function in C - the right way to do it

I'm working on a project in C involving a cellular automaton and I've run into a snag with a function called "get." How can I modify "get" to accept a map and return the value at a specific position? As I delve into pointers and memory allocatio ...

Display tooltips for Autocomplete dropdown options using Vuetify

Just starting out with Vue.js and Vuetify Issue - Need to display tooltips on each dropdown item in v-autocomplete Resolution - included the v-tooltip component in the item template Code: var app = new Vue({ el: "#app", data: { items: [{ ...

Utilizing a combination of a `for` loop and `setInterval

I've been encountering an issue for the past 3-4 hours and have sought solutions in various places like here, here, here, etc... However, I am unable to get it to work in my specific case: var timer_slideshow = {}; var that, that_boss, has_auto, el ...

Ways to initiate a transition upon clicking a button, causing it to switch from being hidden (`display: none`) to visible (`display: block`)

I'm attempting to create a smooth transition effect when a button is clicked, similar to a toggle function, where the content below it seamlessly shifts instead of abruptly moving. The classic example of this is the Bootstrap navbar hamburger menu, wh ...

When attempting to make an .ajax call within the select_node.jstree event for nodes that are not leaf nodes, the call is unsuccessful

When I make an AJAX call using $.ajax, everything works perfectly fine when the select_node.jstree event is triggered, except for non-leaf nodes. In this scenario, although the server receives the Ajax request and sends back the data, the success function ...

Achieving object rotation in three.js by synchronizing with the camera

I'm currently working on making an object follow the camera to create a rifle viewfinder effect. I am using OrbitControl, but I've run into an issue with the camera rotation range. The camera.rotation.y property only goes from -PI/2 to PI/2, even ...

What occurs when the update function returned by React.useState() is invoked?

Just recently, I delved into the world of React hooks and decided to implement a small feature using them. The feature enables hidden texts to be displayed when users click on hyperlinks. Although I managed to make the code work, it appears that there are ...

How to Use a Function to Generate Triangular Shapes in Three.js Using an Array of Vertices

I am diving into the world of JS and THREE.js with the goal of creating a function that performs the following tasks: Combine every 3 values to generate a new vertex, Group every 3 vertices to create a new THREE.Triangle(ta, tb, tc); Keep track of all the ...

Transforming HTML text into clickable links using JavaScript filtering algorithms

Looking to transform HTML content by replacing links with either <img> or <a> tags based on their type. For example, a link like this: https://github.com/dejan/jquery-auto_html/blob/master/jquery.auto_html.js I need a solution that can handl ...

An error popped up while using the fetch API due to an unexpected end of input

fetch('http://www.freegamesforyourwebsite.com/feeds/games/?tag=platform&limit=100&format=json', { method:'GET', mode:'no-cors', dataType: 'json', headers: { 'Accept': 'a ...

custom plugin being disrupted by vue-loader

In the past, I was able to preprocess custom non-HTML tags in a .vue file using Webpack 3 by installing a loader via a plugin. This loader would convert the custom tags into valid HTML/JS code before the vue loader would encounter them and fail. apply(c ...

An uncaught SyntaxError occurred due to an omission of a closing parenthesis after the argument list in code that is otherwise

I have a Javascript code that sends an Ajax request and upon receiving the data, it creates an "a" tag with an onclick event that triggers another method along with a parameter. Below is the implementation: function loadHistory() { var detailsForGe ...

Custom Fields: utilizing multiple checkbox selections to dynamically display relevant information

I'm currently utilizing Advanced Custom Fields within the Wordpress platform, specifically using the checkbox field to exhibit data based on the selected values. The return value for this field is designated as 'Value'. At present, I have t ...

Undefined variable when initializing with ng-init

As a newcomer to AngularJS (and JavaScript in general), I'm currently facing an issue that I could use some help with. Below is the HTML template I am using: <ion-view view-title="Playlists"> <ion-content> <ion-list> ...

Is splitting a PHP array after sorting it your next step?

Below is a var_dump of the array I'm working with: array(6) { [0]=> string(4) "quack" ["DOG"]=> string(4) "quack" [1]=> string(4) "quack" ["CAT"]=> string(4) "quack&quo ...

Using Axios in a Vue component to modify a user's settings

I'm currently working on updating a preference, with the UI example attached below. The default option is set to yes, but I would like to give users the choice to select no as well. I feel like I may be missing something here, so any guidance or assis ...

Using Angular 4 Component to Invoke JavaScript/jQuery Code From an External File

I have written a jQuery code that is executed at ngAfterViewInit(). //myComponent.ts ngAfterViewInit() { $(function () { $('#myElement').click(function (e) { //the code works fine here }); } However, I want t ...

Having trouble getting my ReactJS page to load properly

I am currently linked to my server using the command npm install -g http-server in my terminal, and everything seems to be working smoothly. I just want to confirm if my h1 tag is functional so that I can proceed with creating a practice website. I have a ...

What are the best techniques for optimizing loops when inserting data into a database?

Hi there! Currently, I am facing a challenge in inserting data from an XML file into my MySql database using Sails.js and waterline for the queries. In my database schema, I have two tables named Users and Pets. A user can have multiple pets, and a pet can ...