Determine the index of items within an array of objects in Lodash where a boolean property is set to true

I am new to using lodash after transitioning from C# where I occasionally used LINQ. I have discovered that lodash can be utilized for querying in a LINQ-style manner, but I'm struggling to retrieve the indexes of items in an array of objects with a boolean property set to true using lodash. Can anyone offer some assistance?

My initial attempt:

var indexOfItems = _.find(arrayOfItems, (item) => 
  (item.booleanProperty === true));

However, when I try:

var indexItems: number[] = [];
indexItems = _.times(
  arrayOfItems.length,
  _.find(arrayOfItems, (item) => (item.booleanProperty === true)); 

The second line doesn't compile either.

Thank you!

Answer №1

Using plain JavaScript is all you need to accomplish the same task without relying on lodash.

const data = [{
    booleanProperty: false
  },
  {
    booleanProperty: true
  },
  {
    booleanProperty: false
  },
  {
    booleanProperty: true
  },
  {
    booleanProperty: false
  }
];

const indexItems = data.map((item, index) => item.booleanProperty === true ? index : null).filter((item) => item !== null);


console.log(indexItems)

Answer №2

If you're looking for a single index that meets the condition, you can utilize the findIndex method from either es6 or lodash

data.findIndex(a=>a.booleanProperty)

If you need all the indexes that satisfy your criteria, you have options. You can combine map and filter, or streamline the process with a single reduce. Here's an example using reduce:

data.reduce((r, a, i)=> (a.booleanProperty && r.push(i), r), [])

let data = [{"booleanProperty":false},{"booleanProperty":true},{"booleanProperty":false},{"booleanProperty":true},{"booleanProperty":false}];
    
let indexes = data.reduce((r, a, i)=> (a.booleanProperty && r.push(i), r), []);
  
console.log(indexes);

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

Issue: Incorrect parameters for executing the MySQL statement

Currently, I am working on a nodeJs project and utilizing the npm package mysql2 for connecting to a MySQL database. This is how my MySql Configuration looks like:- let mysql = MYSQL.createConnection({ host: `${config.mysql.host}`, user: `${config.mys ...

Tips on using class-validator @isArray to handle cases where only a single item is received from a query parameter

Currently, I am attempting to validate a request using class-validator to check if it is an array. The inputs are sourced from query parameters like this: /api/items?someTypes=this This is what my request dto resembles: (...) @IsArray() @IsEn ...

The object is classified as 'undetermined' (2571) upon implementation of map() function

Despite conducting a thorough search about this error online, I still haven't been able to find a solution. Let's jump into an example with data that looks like this: const earthData = { distanceFromSun: 149280000, continents: { asia: {a ...

JavaScript issue: Shallow copy does not reflect updates in nested JSON object

Within my coding project, I came across a nested JSON object that looks like this: var jsonObj = { "level1" : { "status" : true, "level2" : {} // with the potential to extend further to level 3, 4, and beyond } } My objective is si ...

After refreshing, the other items stored locally are lost once a new item is added

After refreshing the page, only the item added remains and the rest are lost. How can I make sure all items persist? Here is my code snippet: let buttonsDom = document.querySelectorAll(elementsStr.itemsBtn) const buttons = [... buttonsDom] window.addEven ...

Zoom out the slider when scrolling

Take a look at this link and as you scroll down the page, notice how the image transitions to iPhone. Can anyone provide insight on how this effect is achieved? ...

Creating a dynamic state management system for multiple Collapse components can be achieved by utilizing

I am trying to create a Collapse menu from array data, Currently, when I click on any menu all sub menus expand I believe my issue lies in not being able to set a unique "open" state for each Main menu I want to avoid assigning a "state" to accommodate ...

Formatting dates in a C# MVC application after parsing JSON

I am working on an MVC application that retrieves data from a SQL database and passes it to a view. One of the views contains a Kendo grid that displays the data, including a date column. The date data is stored in the SQL database as DateTime, while the m ...

Crafting interactive image checkboxes

At present, the checkboxes in my application are quite basic with labels. However, our app designer has requested that we revamp this feature and make it more appealing by using clickable images that still function like checkboxes. Allow me to provide an ...

The repairDatabase function cannot be found in the Collection.rawDatabase() method

Seeking guidance on repairing a database within Meteor. Currently executing the following code: Meteor.methods({ 'repairDB'(){ Users.rawDatabase().repairDatabase(); return true; } }); Encountering the following error: I20170630-18: ...

Exploring the elements within the ContentChildren directive in Angular

Presenting my component: import { Component, OnInit, ContentChildren, QueryList } from '@angular/core'; import { IconBoxComponent } from '../icon-box/icon-box.component'; @Component({ selector: 'app-three-icon-box', temp ...

Transferring information to the controller and refreshing the interface (Single-page design)

I'm stuck on a personal project and could really use some help. If anyone has any feedback, it would be greatly appreciated. Thanks in advance. In my index.php file, I have a div with the id main-container. Inside this container, there are two separa ...

Facing an issue where WordPress AJAX is not showing the expected content

Currently, I am in the process of creating a WordPress website that will feature an initial display of two rows of images. Upon clicking a button, two more rows should dynamically appear. There are four key files involved in this project: case-study-ca ...

Prevent selection on all elements except for input fields with the type of text

I am facing a challenge where I need to prevent selection on a website page for everything except input[type=text] elements. The answer provided in this accepted response to a similar query almost solves the issue. However, it doesn't stop users from ...

How can you craft a dynamic radial mask to animate layered images?

My goal is to have two circular SVG images layered on top of each other, with the top image in grayscale and the bottom image in full color. I want to be able to gradually remove the top image based on a percentage from 1-100, similar to how hands sweep a ...

Maintain fullcalendar event filtering across multiple renderings

I currently have a fullcalendar that initially displays all events. I am using a select dropdown to filter the events, which works well. However, when the calendar re-renders after moving to the next month, it shows all events again. Here is my calendar in ...

I'm having some trouble with my jQuery.get() function in the javascript Saturday(), can anyone help me figure out what I'm doing wrong?

Can anyone help me troubleshoot my jQuery.get() method in the saturday() JavaScript function? Here is the code snippet I have been working on. This is what I have in my index.html file: <html> <head> <title>jVectorMap demo</title> ...

Issue with Discord.js (14.1) - Message Handling Unresponsive

After developing a sizable Discord Bot in Python, I decided to expand my skills and start learning JS. Despite thoroughly studying the documentation and comparing with my original Python Bot regarding intents, I am facing difficulties getting the message ...

I am in need of creating a specialized Gulp task that can effectively strip out attributes from my HTML code

I am in need of a Gulp task that can iterate through all specified HTML documents and eliminate specific attributes (such as style=""). I initially attempted to accomplish this task the same way I would do it via the browser, but it seems that's not p ...

Utilize AngularJS to inject a service into a module without assigning it to a variable, enabling easier minification

Currently, I am attempting to decrease the size of my AngularJS JavaScript code (using SquishIt). Within my module, there is a service injected as a function argument, as shown below. var myapp = angular.module('myapp', ['ngSanitize'] ...