The findIndex() method will consistently return a value of -1 when used on an array

I am struggling to find a solution for the following problem. Instead of returning 1, the index is always -1 in this case.

Can anyone assist me with this?

let allRules = [{ruleName: "a"}, {ruleName: "b"}, {ruleName: "c"}]
let name = "b"
let index = allRules.findIndex(x => {
  console.log(x.ruleName)
  x.ruleName === name
})
console.log(index)

Answer №1

To ensure proper functionality, remember to utilize the return keyword when working with callback methods that include empty curly braces:

let allItems = [{itemName: "apple"}, {itemName: "banana"}, {itemName: "cherry"}]
let itemToFind = "banana"
let itemIndex = allItems.findIndex(x => {
  console.log(x.itemName)
  return x.itemName == itemToFind
})
console.log(itemIndex)

Here is an example of a similar function without the return statement:

let allItems = [{itemName: "apple"}, {itemName: "banana"}, {itemName: "cherry"}]
let itemToFind = "banana"
let itemIndex = allItems.findIndex(x => x.itemName == itemToFind)
console.log(itemIndex)

Answer №2

To solve the problem, make sure to include a return statement in your code.

let allRules = [{ruleName: "a"}, {ruleName: "b"}, {ruleName: "c"}]
let name = "b"
let index = allRules.findIndex(x => {
  console.log(x.ruleName)
  return x.ruleName === name
})
console.log(index)

Answer №3

According to @Nick Parsons' comment, it is necessary to include a return statement in your code.

let allRules = [{ruleName: "a"}, {ruleName: "b"}, {ruleName: "c"}]
let name = "b"
let index = allRules.findIndex(x => {
  console.log(x.ruleName);
  return x.ruleName === name;
})
console.log(index)

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

The MongoDB GridFS is refusing to accept the buffer being written

Hey everyone, I've been working on this issue for nearly a day now and can't seem to figure it out. I'm utilizing multer's inMemory flag to upload an image from my website. My approach involves writing the buffer received from multer to ...

Issues with Javascript causing MongoDB batch insert to fail

I need assistance with optimizing my Javascript code. I have created a script to insert multiple records into a collection at once using "insertMany()". However, the code I wrote is not functioning correctly: var batch = []; for (i=0; i<10; i++) { ...

Using JQuery, retrieve all field values on click, excluding the value of the closest field in each row

I have a dynamic table where each row consists of an input field and a button. I am searching for a simpler way to select all input fields except the one in the current row when clicking the button in each row. All input fields have the same name and the r ...

Learn the process of using Angular Js to compare checkbox values with stored comma-separated values in a database

When displaying amenity checkbox options using ng-repeat of a JSON array and saving them into the database as comma-separated IDs like "1,3,7" within a single string, the challenge arises when needing to edit the amenities. This is due to retrieving the ex ...

Is there an alternative method to retrieve model value on controller in Angular bootstrap ngbdatepicker since the (change) method has been removed?

Currently, I am working with ngbdatepicker in Bootstrap. I have added a datepicker selector to appcomponent.html and the datepicker is showing up. Now, I need to retrieve that model value into the controller so that I can pass it to the parent appcomponent ...

Illuminate objects using three.js

My expertise in shaders and three.js is limited, however I am currently experimenting with creating a dynamic glowing effect similar to lights being flicked on and off. Currently, I am adjusting the color saturation and lightness which somewhat achieves ...

minimize javascript syntax (stackoverflow 2022)

I'm struggling with this puzzle game. Sometimes, when I start a new game, the pieces get shuffled incorrectly. I tried adding a function to fix it, but it doesn't seem to be working. It's really frustrating and I want to simplify the code as ...

Retrieve the value of an array element only if the following element is not part of a series

Check out this array $newArray = array( 0 => 10, 1 => 9, 2 => 8, 3 => 6, 4=> 4 ); I need to retrieve the value 6 from the array. It seems like the series is broken because 7 is missing before this value. Can someone assist me with a quick ...

Using Google Cloud Function to write and read a JSON file

I'm currently tackling a project that involves comparing two JSON files fetched at different time intervals. Essentially, it's a continuous cron job that retrieves a new JSON response from an API every 20 seconds and compares it with the previous ...

Locate the positions of 2 identification numbers within a Mongoose array

I am currently working on developing a middleware that validates if a conversation exists between two users in the database. If the conversation does not exist, the middleware will create a new conversation. I am attempting to utilize Mongoose's $in o ...

Searching for the largest sum of greatest common divisors in an array without repeating values

Given an array with an even number of elements, the task is to select n/2 (where n is the size of the array) pairs and calculate their greatest common divisor (GCD) in such a way that the sum of all GCDs is maximized. Once an element from the array is used ...

Filtering input for multiple header columns in an Angular table

A complex Angular table structure has been implemented with three columns. Each column header contains an input field for Stock Number, Case, and Availability. Users have the flexibility to search using a Single Input (Stock Number OR Case OR Availability ...

Encountering an issue with Angular 1.6 and webpack: controller registration problem

Currently developing a small application with Angular for the frontend, and my frontend module is structured as follows: https://i.stack.imgur.com/tjfPB.png In the app.js file, the main Angular module 'weatherApp' is defined: angular.module(&a ...

What is the best way to retrieve search queries from suggestqueries.google.com through a fetch request, or is there another method to obtain Google suggestions?

https://i.sstatic.net/1rTiC.png I have recently created a Vue.JS new tab page and I'm looking to integrate Google suggestions into the search bar. After some research, I stumbled upon an API that seems like it could help me achieve this. However, whe ...

Organize and refine content using JavaScript

Portfolio Website Project For a university project, I took on the challenge of coding a portfolio website for a friend. This endeavor led me to explore Vue.js and delve deeper into JavaScript as a whole. Check out the website here! While navigating thro ...

Problem with resizing in CSS and jQuery

I need help creating a chatbox that can be resized. I've almost got it, but the bottom part of the chatbox detaches when I resize it. Also, I'm having trouble making the userList a fixed size that won't be affected by resizing. Check out th ...

Using immer JS to update a nested value has been successfully completed

What is the most efficient way to recursively change a value using a recursive function call in a Produce of Immer? The WhatsappState represents the general reducer type, with Message being the message structure for the application/db. type WhatsappState = ...

Using Laravel to submit a form with identical input names via AJAX

Seeking assistance with my ajax function. A form I have is submitting data with the same input name. Without using JavaScript, I can insert multiple input data with the same name easily, Here is the structure of the submitted data {"_token":& ...

Looking for a way to transfer the value of a variable to a PHP variable using any script or code in PHP prior to submitting a form?

Within this form, the script dynamically updates the module dropdown list based on the selected project from the dropdown box. The value of the module list is captured in a text field with id='mm', and an alert box displays the value after each s ...

Finding multiple locations with Google Maps API Geocoding

I've created a small JavaScript code to geocode various locations and display them on a map. While I can successfully plot a single location, I'm struggling to get it working for multiple locations. Below is the code that currently works for one ...