Is there a way to streamline this function call that appears to be redundantly repeating the same actions?

I have developed a function to search for blog posts, prioritizing titles over excerpts and excerpts over content when added to the containsQuery array. While the code seems to be working well, I have noticed that there is a lot of redundant code. How can I streamline this process?

const findArticles = (posts: any[], query: string) => {
    const containsQuery: any[] = []
    let words
    let i: number

    if (query.includes(' ')) {
      words = query.toLowerCase().split(' ')
    }

    const findArticle = (multipleWords:boolean, posts: any[], query:string, searchedParam:string, words:string[] = [],) => {
      if (multipleWords === false) {
        for (i = 0; i < posts.length; i++) {
          if (posts[i][`${searchedParam}`].toLowerCase().includes(query.toLowerCase())) {
            containsQuery.push(posts[i])
          }
        }
      } else {
        for (i = 0; i < posts.length; i++) {
          if(words.every(q => posts[i][`${searchedParam}`].toLowerCase().includes(q))) {
            containsQuery.push(posts[i])
          }
        }
      }
     
    }

    if (words) {
      findArticle(true,  posts, query, 'title', words,)
     } else {
      findArticle(false, posts, query, 'title')
     }

     if (words) {
      findArticle(true,  posts, query, 'excerpt', words,)
     } else {
      findArticle(false, posts, query, 'excerpt')
     }

     if (words) {
      findArticle(true,  posts, query, 'content', words,)
     } else {
      findArticle(false, posts, query, 'content')
     }

    const oneOfKind = Array.from(new Set(containsQuery.map(article => article.id))).map(id => {
      return containsQuery.find(a => a.id === id)
    })
    
    return oneOfKind
  }

To avoid duplicates and improve efficiency, I attempted to create a copy of the posts using my own const copyOfPosts = posts and then modify it, but this caused some issues in the code. The current code structure appears to be the most effective way to achieve the desired outcome. Any suggestions for improvement are greatly appreciated.

if (posts[i][`${searchedParam}`].toLowerCase().includes(query.toLowerCase())) {
            containsQuery.push(posts[i])
            copyOfPosts.splice(i, 1)
          }

Answer №1

Here:

const findArticle = (multipleWords:boolean, posts: any[], query:string, searchedParam:string, words:string[]) => {
    const containsQuery: any[] = []
    if (multipleWords === false) {
        for (let i = 0; i < posts.length; i++) {
            if (posts[i][`${searchedParam}`].toLowerCase().includes(query.toLowerCase())) {
                containsQuery.push(posts[i])
            }
        }
    } else {
        for (let i = 0; i < posts.length; i++) {
            if(words.every(q => posts[i][`${searchedParam}`].toLowerCase().includes(q))) {
                containsQuery.push(posts[i])
            }
        }
    }
    return containsQuery
}

const findArticles = (posts: any[], query: string) => {

    let words = query.includes(' ') ? query.toLocaleLowerCase().split(' ') : [] 

    const containsQuery = findArticle(true, posts, query, 'title', words)

    containsQuery.push(...findArticle(true, posts, query, 'excerpt', words))

    containsQuery.push(...findArticle(true, posts, query, 'content', words))

    const oneOfKind = Array.from(new Set(containsQuery.map(article => article.id))).map(id => {
        return containsQuery.find(a => a.id === id)
    })
    
    return oneOfKind
}

I am planning to optimize the findArticle function in my own way.

const findArticle = (multipleWords:boolean, posts: any[], query:string, searchedParam:string, words:string[]) => {
    const containsQuery: any[] = []
    if (multipleWords === false) {
        for (let i = 0; i < posts.length; i++) {
            if (posts[i][`${searchedParam}`].toLowerCase().includes(query.toLowerCase())) {
                containsQuery.push(posts[i])
            }
        }

        return containsQuery
    } 
    
    for (let i = 0; i < posts.length; i++) {
        if(words.every(q => posts[i][`${searchedParam}`].toLowerCase().includes(q))) {
            containsQuery.push(posts[i])
        }
    }
    return containsQuery
}

This approach avoids using an excessive else statement, although some may argue about having two return statements.

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

Having trouble choosing a subitem from a dropdown menu in Vuejs?

An example can be found at https://jsfiddle.net/79epsrmw/. However, the issue arises when targeting the item1 sub-menu in VS Code even after assigning a unique id. var app = new Vue({ el: '#app', data: { menuItems: [ ...

Creating dynamic charts in Javascript using Firebase

My dad recently asked me to enhance our motor home by integrating an Arduino with Firebase to monitor the water and propane tanks. He's hoping to be able to check tank levels from his phone so he can see when they need refilling. I've successful ...

Tips for efficiently reorganizing repetitive ggplot parameters?

What is the most effective approach to optimize these recurring plot settings? I attempted to create a function to handle this but it was unsuccessful. What is the recommended method to accomplish this in R? Check out the sample code below: ggplot(df.off ...

Is the child constantly updating due to a function call?

Having difficulty navigating the intricacies where a child keeps re-rendering due to passing a function from the parent, which in turn references an editor's value in draftjs. function Parent() { const [doSomethingValue, setDoSomethingValue] = Re ...

Having difficulty in utilizing localStorage to update the state

I've attempted to log back in using the stored credentials, however it's not working despite trying everything. The dispatch function is functioning properly with the form, but not when accessing localStorage. App.tsx : useEffect(() => { ...

The compilation of PKG using Axios 1.x encounters an error

Despite attempting numerous strategies, I have not been successful. I developed a Node.js application with API requests managed using axios. However, I am unable to convert it into an executable file. Trying to downgrade Axios to version 0.27.0 resolved th ...

Error in hook order occurs when rendering various components

A discrepancy was encountered in React when attempting to render different components Warning: React has detected a change in the order of Hooks called by GenericDialog. This can result in bugs and errors if left unresolved. Previous render Next ren ...

Deliver an assured result to a variable within the angular.extend() function

Can someone provide guidance on how to set myVar to a value returned from an asynchronous service method in the following example? angular.extend(this, { myVar: (function() { getVal(); })() }); function getVal() { var d = $q.defer(); ...

Debugging Success Message Display Issue in JavaScript

$.ajax({ type: "POST", url:'/saveLayout', data: {id : layoutId, section : arrSection}, success: function(response){ $('#successMsg').addClass("errorBox"); document.getEleme ...

Sharing specific props with deeply nested components in React

I am experimenting with configuring props for children components. In this example, I am testing a function to target any child, whether nested or not, with the prop swipeMe. It works perfectly when the render function contains only a single child, like ...

Having trouble configuring the sticky-footer correctly

Currently enrolled in a web development course on Udemy, I am facing an issue with the footer on my webpage. Even after setting its CSS position to relative, the footer overlaps the content when more data is added. However, removing this positioning causes ...

What is the best way to locate the key with the greatest value in an array that is less than or equal to a certain

In my data structure, I have an array that maps user levels to the minimum points required for each level. Here's how it looks: $userLevels = array(0 => 0, 1 => 400, 2 => 800); The keys represent user levels and the values represent the min ...

My AngularJS module seems to be malfunctioning

After spending a significant amount of time on this, I am really hoping for some assistance. I am currently working on creating a module that will generate a directive and controller for the header section of my AngularJS site. Despite not encountering any ...

The AJAX response doesn't seem to be halting

My AJAX request looks like this: $.ajax({ url: "AutoRFQ_Vendors_ST.aspx/BindVesselGrid", type: "POST", timeout: 3000, data: JSON.stringify(sendingdata), ...

Display the Material UI Switch in an active state even when the "checked" value is set to false

While using Material UI Switches with Formik, I've encountered an issue. When I toggle the switch to 'enable,' it automatically sets the value in Formik to "true," and when I toggle it to 'disable,' it sets the value in Formik to " ...

"Troubleshooting problem with fetching JSON data for Highcharts

As a relative newcomer to web development, my usual focus is on server-side work. Currently, I'm diving into a fun little electronic project where a Netduino server handles JSON requests within my LAN. The JSON response format from the Netduino looks ...

Tips for extracting and dividing the value of an input field using jQuery

My system includes an input search field where I can enter the make and/or model of a vehicle to conduct a search based on that term. The challenge arises when attempting to distinguish between the make and model, especially for makes with multiple words ...

What could be preventing the array from updating after subscribing to the service?

Attempting to fetch a list of movies from a Web API server on my localhost. The server does provide data when called with a Get request using the HttpClient module, but struggling to display it. MovieList Component import { Component, OnInit } from &apos ...

Issues with setting headers after they have been sent - Can you explain why?

How am I setting a header after it has been sent to the client? Here is the code snippet: When a form is submitted, a post ajax request is triggered which returns a JSON object to the client. I have commented out most of the code to troubleshoot, and cur ...

Exploring the possibilities of using the typeof operator within an Event

I want to log some information if the input value is a number. However, I am facing an issue where it's not working and no bugs are appearing. Here is a snippet of code from CodePen (https://codepen.io/matoung/pen/KBNmPP) let button = document.que ...