Is it possible for the `findIndex` method in EcmaScript6 to return multiple values at once

When delving into ES6, I came across a situation where I needed to find the index of multiple items in an Array. However, I found that it only returned the index of the first item that matched my condition or callback function.

For example, let's say we have an Array with ages and we want the indexes of all ages greater than or equal to 18.

let ages = [12,15, 18, 17, 21];
console.log(`Over 18: ${ages.findIndex(item => item >= 18)}`);
// expected output: [2,4]
// actual output: 2

So I'm curious if the Array.prototype.findIndex() method only returns the index of the first item that matches, or -1 if no item satisfies the condition. Is there a way to achieve this using ES6?


Thank you

Answer №1

To implement this functionality, utilize the .map() method as shown below:

let ages = [12, 15, 18, 17, 21];
let indexes = ages.map((elm, idx) => elm >= 18 ? idx : '').filter(String);
console.log( indexes );

The syntax for utilizing the .map() method is as follows:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

In this syntax, both currentValue and index can be harnessed according to our needs.

An example of a reusable function for this task is demonstrated below:

const ages = [12, 15, 18, 17, 21];
const getAllIndexes = (arr, val) => {
  return arr.map((elm, idx) => elm >= val ? idx : '').filter(String);
}

console.log(getAllIndexes(ages, 18));
console.log(getAllIndexes(ages, 17));

Answer №2

The findIndex() function is utilized to locate the index of the initial element in the array that meets the criteria set by the testing function. If no elements satisfy the condition, -1 is returned.

An alternative approach involves utilizing reduce. By employing concat, the index can be added to the accumulator when the number is equal to or greater than 18.

let ages = [12, 15, 18, 17, 21];

let result = ages.reduce((c, v, i) => v >=18 ? c.concat(i) : c, []);

console.log(result);

Answer №3

For a straightforward solution, utilize the Array.reduce() method to create an array containing the indexes of all ages that are greater than 18.

let ages = [12,15, 18, 17, 21];
var result = ages.reduce((a,curr,index)=>{
  if(curr >= 18)
    a.push(index);
  return a;
},[]);
console.log(result);

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 specified property 'slug' is not found within the designated type 'ParsedUrlQuery | undefined'

I am faced with an issue in my code where I am attempting to retrieve the path of my page within the getServerSideProps function. However, I have encountered a problem as the type of params is currently an object. How can I convert this object into a stri ...

Delete the selected background color from custom drop-down lists in versions of Internet Explorer 9 and earlier

In my asp.net application, I have a dropdown element. I am trying to remove the default blue background color that appears when the dropdown is selected, as shown in the image below. I have tried all the solutions provided in this link, but none of them s ...

The Angular routing functionality appears to be malfunctioning

I am currently implementing routing in my project using basic angular route with Angular 1.3.0. Here is the content of my app.js file: 'use strict'; var routerApp = angular.module('mcw', [ 'ngRoute', 'mcw.controll ...

Creating a drop-down menu that aligns perfectly under the bar in Material-UI: What you need to know

While working with Material-UI, I encountered a problem with my drop-down menu. Every time I click on it, it covers the bar instead of appearing below it (see image links below). https://i.stack.imgur.com/1Y8CL.jpg https://i.stack.imgur.com/emf87.jpg Is ...

Algorithm for dividing two sets into "unique to Set A", "intersection of Set A and Set B", and "unique to Set B"

I'm faced with a scenario where I have two arrays that need to be partitioned into 3 separate arrays: elements exclusive to array A elements exclusive to array B elements present in both arrays A and B For example: A = [1, 4, 3, 2] B = [2, 6, 5, 3 ...

The initialization of the R Shiny HTML canvas does not occur until the page is resized

I am currently facing an issue while integrating an HTML page with a canvas into my shiny R application using includeHTML(). The packages I am using are shiny, shinydashboard, shinycssloaders, dplyr, and DT. Everything is working perfectly fine except for ...

Modify the CSS class by utilizing ngClass

Is it achievable to modify only one out of multiple classes assigned to an element without affecting the others? Illustration: <span ng-class="{'result warning' : error, 'result passing' : !error}"></span> In this code sn ...

Navigate through the overlay's content by scrolling

Objective: Looking to implement a scroll feature for long content. Issue: Not sure how to create a scroll that allows users to navigate through lengthy content. Thank you! function openNav() { document.getElementById("myNav").style.height = "1 ...

Tips for displaying a refresh indicator while making an ajax call for refreshing data:

I have successfully implemented jQuery code that refreshes a specific div every 10 seconds without reloading the entire page. However, during this refresh process, the user does not visually perceive any changes happening in the browser. While there are n ...

Searching for dates within a range on DataTables using CodeIgniter

Can someone assist me in displaying data within a selected date range? Here is the code snippet I have so far: Below is the code for displaying the data tables: View <div class="box-body"> <div class="table-responsive"> ...

The URL does not contain the complete hash

I'm currently working on a gallery using Jquery Elastislide. var imageIndex = 0; if (window.location.hash) { var imageIndexStr = window.location.hash.replace('#',''); // removing # imageIndex = parseInt(imageIndexStr, 0) ...

Notes on using touch devices with Angular

My goal is to make my Angular application capable of displaying a footnote on mobile devices when text injected with nativeElement.innerHTML is clicked. I attempted to explain this before but feel that I didn't do it justice, so here's another sh ...

The functionality of the Youtube API is not compatible with a dynamically generated array of objects

Encountering an unusual problem with the Youtube API... I am in the process of developing a script that identifies all Youtube videos on a webpage and then replaces them using the Youtube API. This approach enables me to monitor API events like video compl ...

Set default selected value for dropdown list using radio buttons

Could anyone provide guidance on how to reset a dropdown list value using a radio button selection? Specifically, I need the dropdown list to reset to its default "selected" option when a particular radio button is clicked. Any recommended approaches usin ...

Clicking the React Todo Delete Button instantly clears out all tasks on the list

I am dealing with 2 files: App.js import React, { Component } from 'react'; import './App.css'; import ToDo from './components/ToDo.js'; class App extends Component { constru ...

Determining the Clicked Button in ReactJS

I need help with a simple coding requirement that involves detecting which button is clicked. Below is the code snippet: import React, { useState } from 'react' const App = () => { const data = [ ['Hotel 1A', ['A']], ...

Explore the inner workings and file contents of a package using the NPM registry API, by accessing a detailed JSON response

Can the NPM registry API be utilized to access an endpoint like https://registry.npmjs.org/jquery And examine the Tarbells structure and internal files without the need to download the package, in a JSON response similar to: { files: { js: registr ...

Struct object not found within nested array during JSON unmarshaling

Encountered an issue with unmarshalling a string back to a struct object that contains a nested array of struct objects. The problem is demonstrated in the following code snippet: The JSON string is as follows: const myStr = `{ "name": "test_session1", ...

Mask the input numbers to a specific format

I have a custom input component that I use to manage user inputs. export const MyCustomInput = (props) => { const { name, required, value, label, onChange, type, icon, } = props const Icon = () => (icon ? <div cl ...

Obtain the YouTube video identifier from a YouTube embedded link

Is there a way to extract just the YouTube ID from a given URL? https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0 $(".youtube").click(function () { console.log(this.href.replace(new RegExp("em ...