Seeking out the index of each instance of a specific element within an array using Ramda.js techniques

I am currently attempting to locate the index of all occurrences of both Header and Footer within an array.

var arr = [
'data',
'data',
'data',
'data',
'Header',
'data',
'data',
'data',
'Footer',
'data',
'Header',
'data',
'Footer',
'data'
];

While I am familiar with how to achieve this using vanilla JavaScript (How to find index of all occurrences of element in array?), I am curious to see how it can be accomplished using functional programming, specifically with ramda.js.

I have been able to find the index of the first occurrence using

R.findIndex(R.test(_regexForHeader))
, but I am struggling to figure out how to loop through the entire array. Any assistance would be greatly appreciated.

Answer №1

@pierrebeitz's response is spot-on, especially when it comes to needing access to indices while looping through a list. Ramda offers an R.addIndex function that can be used to customize functions like map to include the index along with each element during iteration.

If you prefer, you can simplify the nesting in the example by using a composition pipeline:

const zipWithIndex = addIndex(map)(pair);

const isHeaderOrFooter = either(equals('Header'), equals('Footer'));

const hfIndices = pipe(
  zipWithIndex,
  filter(pipe(head, isHeaderOrFooter)),
  map(nth(1))
);

hfIndices(arr);

However, it's important to note that both of these methods require iterating over the list multiple times. While this may not be an issue for smaller lists, it's worth considering using R.into for larger lists, as it combines the map and filter operations into a transducer, allowing for a more efficient single pass over the list (check out for a good introduction to transducers).

To implement this with the previous example, simply switch the composition from pipe to compose (since transducer functions compose in reverse order) and wrap it with into.

const hfIndices = into([], compose(
  zipWithIndex,
  filter(pipe(head, isHeaderOrFooter)),
  map(nth(1))
));

Answer №2

While I may not be completely immersed in FP, I do believe that in order to manipulate data effectively, you need to first "generate" the data you want to work with. You then need to add an index to apply your filter afterwards:

 var arr = ['data', 'data', 'data', 'data', 'Header', 'data', 'data', 'data', 'Footer', 'data', 'Header', 'data', 'Footer', 'data'];

R.map((e) => e[1], 
  R.filter(val => val[0] == 'Header' || val[0] == 'Footer', 
    R.addIndex(R.map)((e, i) => [e,i], arr)
  )
);
// => [4, 8, 10, 12]

Although this solution may not be the most intricate, it should provide a good starting point for your needs!

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

What is the best way to divide an array while extracting data from a JSON object using

Currently, I am parsing the json data. My goal is to find a specific property within the json object that contains two nested arrays (list and array). However, when extracting the values, they are all being stored in a single array. Is there a way to separ ...

Updating information within an ArcGIS Service using REST and JSON using jQuery/JavaScript

I've been attempting to update information in a feature within an arcgis service using REST and JSON. I've created a function that is supposed to be called, but the output I'm receiving is not providing me with any clear direction. I am als ...

What is the best way to retrieve the outcome of a node-sqlite3 query beyond the scope of db.get()?

I'm attempting to validate whether the sha256 hash stored in my sqlite database corresponds with the sha256 hash of the password that the user transmitted to my NodeJS server. The Auth() method is meant to deliver either a true or false result. Is the ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...

Steps to remove a specific child element using jQuery:

CSS: <h1><br style="clear:both;"></h1> I am currently working on a project that involves using the Wikipedia API. One issue I've run into is cleaning up the raw HTML output from Wikipedia, specifically dealing with removing a speci ...

Tips for creating an Enumerable 'similarity' search using linq.js

I have a JSON array that looks like this: [ { "_Id": "0001", "_PatentId": "0000", "_Text": "Employee", "_Value": "employee", "_PermissionLevel": 55 }, { "_Id": "0002", "_PatentId": "0000", "_Text": "Employees" ...

Failed to establish Modbus TCP connection

Currently, I am utilizing the "Panasonic FP7" master PLC along with their official software "FPWIN GR7" to monitor data flow on my PC. However, since the software lacks certain functions, I have decided to develop a solution using nodeJS. Below is the code ...

Why does Res.send return an empty object when console.log indicates it is not empty?

I am currently facing a challenge while using the Google Sheets API with Express, as I have limited experience with JavaScript. My goal is to pass a JSON object from Express to React, but for some reason, when I send the object, it appears empty on the fro ...

Ways to add a string to an array as a labeled object in javascript?

Is there a way to manipulate the array in imageCollection to achieve the format of the array in carouselPhotos as shown below? export default class HomeScreen extends Component { state = { imageCollection: [ { name: "P ...

Unable to perform dynamic query with $in operator in Mongoose find method

I am currently utilizing Node.js along with Mongoose version 5+ to create a dynamic query in my database. The variable filterField represents the field name, while filterValues is an array. Here is an example of how my code looks: if (req.currentUser.acti ...

Troubleshooting inactive CSS hover animation

Greetings! I'm facing an issue with a CSS hover animation. Here are two demos I've created: In the first DEMO, the animation works perfectly. However, in the second DEMO, it doesn't seem to be functioning. On the second demo, there are two ...

Transitioning to Meteor and React or Immigrating to Meteor

Are there any available resources specifically designed for Meteor that can assist with loading large assets (ranging from 20MB to 80MB) primarily for offline use? Currently, I am working on a project using Vanilla JS on the client side, but I am contempl ...

What is the process for retrieving my dates from local storage and displaying them without the time?

Having an event form, I collect information and store it in local storage without using an API. However, I face a challenge when extracting the startdate and enddate out of localstorage and formatting them as dd-mm-yyyy instead of yyyy-mm-ddT00:00:00.000Z. ...

Why are the UI components (`Card Number`, `MM/YY`, `CVC`) not being displayed in the React app when using Card

Having an issue where the CardElement Ui component is not visible in the image provided. It should appear above the Order Total: $0 next to the payment method. https://i.sstatic.net/NCK5z.png I've attempted various debugging methods without success. ...

Combining Multiple .ts Files into a Single File: A Simplified Application Structure with TypeScript 1.8

Currently, I am in the process of developing an Electron application and I have decided to implement TypeScript for this project. While TypeScript essentially boils down to JavaScript in the end, my familiarity with it makes the transition seamless. As of ...

Is there a way to customize event property setters such as event.pageX in JavaScript?

Is there a way to bypass event.pageX and event.pageY for all events? This is because IE10+ has a known bug where it sometimes returns floating point positions instead of integers for pageX/Y. ...

Invalid index when trying to add to an array

I am currently faced with a challenge in modifying an array that I have at hand; +rows: array:31 [▼ 0 => array:2 [▼ 0 => "20190101" 1 => "5" ] 1 => array:2 [▼ 0 => "20190102" 1 => "15" ] ...

What is the process for requiring web workers in npm using require()?

I have a setup using npm and webpack, and a part of my application requires Web Workers. The traditional way to create web workers is by using the syntax: var worker = new Worker('path/to/external/js/file.js'); In my npm environment, this metho ...

Determining the unique values within a sub-array across various queries

I am facing a challenge with an array that can hold up to 2X10^5 values. My goal is to run a series of queries on this array, each taking the form of [L,R]. The expected outcome of each query is the count of unique values within the sub-array that starts a ...

Guide to integrating the Google identity services library in a React application

I've encountered an issue with my current code, which has suddenly stopped working: import React, { Component } from "react"; import Auth from "../../helper/auth"; import PropTypes from "prop-types"; import logo from &quo ...