Using JavaScript to filter and reduce an array in order to merge strings together

I want to implement the filter and map approach rather than using a {for} loop to iterate through an array.

Here is my previous code. I was filtering matching strings from an array and combining them.

function oldFunction(data) {
    let dataDeleted = '';
    let each
    for (each of data) {
        if (each.includes('_DELETE')) {
            dataDeleted = dataDeleted + each.substring(0, each.length - 7) + '###';
        }
    }
    dataDeleted = dataDeleted;
    console.log(dataDeleted);
}

oldFunction(['meow_DELETE', 'haga', 'Neigh_DELETE']);

The result is: 'meow###Neigh###'

Now I attempted using the 'filter' and 'reduce' methods, but it doesn't work as expected:

function newMethod(data) {

    const dataDeleted = data
        .filter(d => d.includes('_DELETE'))
        .reduce((deletedData, d) => {
            deletedData.concat(`${d}### `);
        }, '');

    console.log(dataDeleted);
    return dataDeleted;

}

Instead of getting the desired output, this returns 'undefined'. Any advice? Thank you in advance.

Answer №1

Simply return the data in your reducer function.

.reduce((deletedData, d) => {
   return deletedData.concat(`${d}### `);
}, '')

You can also use the shorthand version:

.reduce((deletedData, d) => deletedData.concat(`${d}### `), '')

Answer №2

function removeDeletedData(data) {

    const filteredData = data
        .filter(d => d.includes('_DELETE'))
        .reduce((acc, d) => {
            return acc.concat(`${d}### `);
        }, '');

    return filteredData;

 }

Answer №3

Consider taking a different approach using join() and concat() rather than reduce(). The use of reduce internally iterates the array, which may be something you want to avoid for various reasons. It's worth testing the performance of each method to determine the most optimal solution.

Update: After conducting a comparison on JSperf, it was discovered that my approach is approximately 60-70% slower compared to Quantastical's. Therefore, it is recommended to stick with their method.

Update2: I have adjusted the code based on new requirements from a comment, now utilizing only filter() and reduce().

function updatedMethod(data) {

    const modifiedData = data
        .filter(d => d.includes('_DELETE'))
        .reduce((result, d) => {
          return result.concat(`${result.length ? '###' : ''}${d.replace(/_DELETE$/, '')}`);
        }, '');

    console.log(modifiedData);
    return modifiedData;

}
updatedMethod(['meow_DELETE', 'haga', 'Neigh_DELETE']);

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

Vue throwing ReferenceError when accessing uninitialized variable in Safari browser

Recently, I've encountered a perplexing error message that has me scratching my head. The error message reads as follows: ReferenceError: Cannot access uninitialized variable. This error specifically points to the line of code: const app = createApp(A ...

Wildcard routes for publicly accessible files

I have a collection of "widgets" with both client and server-side .coffee files (client representing Backbone.js model/view and server corresponding to ExpressJS routes), all organized within the main project directory: my-node-expressjs3-project/ src/ ...

Phantom is refusing to initialize/execute angularjs controller methods

I am seeking assistance in generating a PDF file from an HTML page that is controlled by an AngularJS controller. The PDF creation process involves using the Phantom module. My issue is that while data binding works correctly when I navigate to the specifi ...

Drag and release: Place within invalid drop areas

I'm currently developing a drag-and-drop web application using Vue.JS and Vuex Store. The drag-and-drop functionality is based on the HTML Drag and Drop API as outlined in the Mozilla documentation. I have successfully implemented the Dropzone Compone ...

Choosing not to transmit the requested file

I've been attempting to retrieve the following: fetch("https://www.filestackapi.com/api/store/S3?key=MYKEY&filename=teste", { body: "@/C:/Users/Acer/Pictures/1 (2).jpg", headers: { "Content-Type": &quo ...

Dynamic Content in jQuery UI Tooltip

Is it possible to dynamically change the tooltip content as I drag the div that contains the tooltip? I want to display the ui.position.top in the tooltip during the drag event. I have checked the jQuery UI API documentation for tooltip content, which ment ...

Quickest method for skimming through an extremely lengthy document beginning at any specified line X

In my current project, there is a text file that is written to by a python program and read by another program to display on a web browser. JavaScript handles the reading process at the moment, but I am considering moving this functionality to python. The ...

Modifying the style of the HTML placeholder tag

One approach I am taking involves utilizing a placeholder element within my search box input: <input id="searchBarTextbox" type="search" class="k-textbox" placeholder="Search For..." /> My challenge now is to enhance the aesthetics of the placehold ...

I have a question about using Jquery/JS. If I modify an element's HTML, will I still be able to execute other Jquery/JS actions on it?

I have a script that, upon clicking, initiates an ajax call to connect to the database, retrieve the image name, set it inside an <img> tag with the correct path, add a hidden checkbox after it, and then echo it. After receiving the ajax message, I ...

Calculating the number of duplicate elements in an array

I need help with displaying the elements of an array while also counting duplicates. For example: myArr = ['apple', 'apple', 'orange', 'apple', 'banana', 'orange', 'pineapple'] The out ...

Error in consignment and rapid shipping routes

Currently, I am immersed in university coursework centered around building an API with express. The guidelines permit the utilization of additional packages as long as we stay within the specified parameters. I've embarked on employing consign to aut ...

Issue: 'node' is not being recognized when attempting to execute the file using the package.json script

Currently diving into the world of Node.js, I encountered an issue stating "node is not recognized as an internal or external command" whenever I attempt to start my project using either npm start or npm run start. Strangely enough, running node index.js ...

Whenever I try to relocate my HTML file that references three.js, the three.js library seems to malfunction and stop

Something strange is happening... I recently downloaded three.js into a directory named 'brick': git clone https://github.com/mrdoob/three.js.git which created a subdirectory: brick/three.js/ After navigating to brick/three.js/examples ...

Stop the page from scrolling when the mouse hovers over the scene in Firefox

I have a three.js application embedded within a div on a webpage. The issue I am facing is that when using the OrbitControls.js for zooming with the mouse wheel, it also scrolls the entire page. To overcome this, I need to prevent scrolling when the mouse ...

Using v-model in Vue 3 will result in modifications to the table class in Bootstrap 5

Below is a snippet of the code I wrote: <table class="table table-striped"> <tr class="table-dark"> <th>#</th> <th>Column 1</th> <th colspan="3">Column 2</th> </tr> <tr ...

What is the procedure for a parent component to transmit HTML to a child component within Angular?

How can a parent component pass multiple ng-templates to a child component? For example, the parent component includes multiple ng-templates: <app-childcomponent> <ng-template>Item A</ng-template> <ng-template>Item B</n ...

What is the best way to invoke a function with multiple parameters in TypeScript?

I have a function that manipulates a specified query string, along with another version that always uses window.location.search. Here is the code snippet: class MyClass { public changeQuery(query: string; exclude: boolean = true; ...values: string[]): st ...

What is the best way to determine if a variable is an object array or not?

I need to determine whether a variable is an Object array or not. Consider the following example data: var myColumnDefs = [ {key:"label", sortable:true, resizeable:true}, {key:"notes", sortable:true,resizeab ...

Maintain the expanded menu even after selecting a sub-item using jQuery

After conducting a thorough search, I was unable to find exactly what I needed. I have successfully implemented cookies on my menu so that when the page is reloaded, it remembers which menus were open. However, I noticed that clicking on a sub-item of Hy ...

Issues with jQuery scroll effect not functioning properly in Firefox due to transformation errors

I've encountered an issue with implementing a scroll effect in Firefox. The code works perfectly fine in Chrome, Safari, and Opera, but for some reason, it's not functioning properly in Firefox. I have carefully reviewed the '-moz-transform& ...