Eliminate items from the array if the property of an object includes any of the provided substrings

In an attempt to minimize the objects within arrays that have a property "Title" containing any substring listed in a separate JSON file, I have been struggling with filtering the arrays based on the object's property. However, I believe using the reduce() method would be a more effective approach to achieve this.

The objective is to perform calculations only for objects that are not excluded. For instance, if an object has a Title property different from those specified (qa, quality assurance, software tester), it should be removed from the calculation.

I have been experimenting with different methods to accomplish this task but have not been successful. I think a better approach would be to modify the positionsArray by reducing the objects that should not be included in the calculation, and then perform the necessary calculations.

Here is the function I have been working on:


        calculateSoftwareExperience: async function () {
            fileToCurate.forEach(candidate => {
                const positionsArray = candidate.softwareIndustryPositions;
                console.log(positionsArray)
                //const reducedArray = positionsArray.reduce(x => x.title)
                
                //console.log(positionsArray)
                if (Array.isArray(positionsArray) && positionsArray.length) {
                    // array exists and is not empty
                    positionsArray.forEach(position => {
                        let title = position.title;
                        
                        if (titlesIncluded.some(x => title.includes(x))) {
                            console.log(title)
                            const firstFrom = positionsArray[positionsArray.length - 1].from;
                            const lastTo = positionsArray[0].to;
                            let diff = lastTo - firstFrom;
                            let days = (diff * 1000) / (60 * 60 * 24 * 1000) / 1000;
                            let months = Math.floor(days / 31);
                            //console.log(firstFrom, "to", lastTo, "diff = ", months);
                            candidate.softwareIndustryExp = months;
                            //console.log(months)
                        }
                    });
                } else {
                    candidate.softwareIndustryExp = 0;
                }
            });
        },
    

Output of positionsArray:


        [
            {
                flagged: false,
                from: 2019-10-31T23:00:00.000Z,
                to: 2020-01-31T23:00:00.000Z,
                title: 'junior manual tester'
            },
            {
                flagged: false,
                from: 2018-05-31T22:00:00.000Z,
                to: 2019-09-30T22:00:00.000Z,
                title: 'junior administrator'
            },
            {
                flagged: false,
                from: 2016-03-31T22:00:00.000Z,
                to: 2016-03-31T22:00:00.000Z,
                title: 'praktykant'
            }
        ]
    

Input with specified substrings:


        "titlesIncluded": [
            "qa",
            "quality engineer",
            "qa automation",
            "software tester",
            "qa engineer"
        ],
    

Answer №1

I tackled this problem using my own approach as I couldn't figure it out with the reduce() method. Essentially, what I did was create a new object, filter it by the title property, push each object into an array, and perform the necessary calculations. Take a look at my implementation:

    calculateSoftwareExperience: async function () {
      fileToCurate.forEach(candidate => {
        const positionsArray = candidate.softwareIndustryPositions;
        
        if (Array.isArray(positionsArray) && positionsArray.length) {
          let titlesArray = [];
          positionsArray.forEach(position => {
            let title = position.title;
            if (titlesIncluded.some(x => title.includes(x))) {
              let pos = {};
              pos.title = title;
              pos.from = position.from;
              pos.to = position.to;
              titlesArray.push(position);
            }
          });
          
          if (Array.isArray(titlesArray) && titlesArray.length) {
            const firstFrom = titlesArray[titlesArray.length - 1].from;
            const lastTo = titlesArray[0].to;
            let diff = lastTo - firstFrom;
            let days = (diff * 1000) / (60 * 60 * 24 * 1000) / 1000;
            let months = Math.floor(days / 31);
            candidate.softwareIndustryExp = months;
          } else {
            candidate.softwareIndustryExp = 0;
          }
        } else {
          candidate.softwareIndustryExp = 0;
        }
      });
    },

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

Datatables.js columns mismatch issue

Currently, I am facing an issue while trying to implement a datatables functionality using datatables.js in my asp.net core NET 7.0 project. The error message that keeps popping up states that there is an incorrect number of columns in the table. I have se ...

When accessing the innerHTML and outerHTML properties on an HTMLElement, they may return undefined without triggering

Task: My goal is to take an HTML string, make changes to certain attributes of image tags within it, and then return the modified HTML string. The function I have developed follows these steps: private resolveImagesInHTML (body: string): string { le ...

Is there a way to continue a failed fetch request?

I am curious about the possibility of resuming an incomplete fetch request if it fails due to a non-code-related issue, like a lost network connection. In one of my current projects, we send a large download via AJAX to the client after they log in. This ...

What is the optimal method for invoking a Javascript function via a hyperlink?

I'm looking to include links on my website that will activate a javascript function when clicked, and I do not want these links to be underlined. Additionally, I want the cursor to change to a standard pointer. What is the most effective way to achiev ...

Printing feature not functioning properly on Internet Explorer version 11

Currently, I am facing an issue with printing a document using a blob URL and iFrame. Everything works perfectly in Chrome, but unfortunately, it's not functioning properly in IE browser. I need guidance on how to successfully print a blob URL that i ...

Adjust the text area to automatically expand or shrink based on the text it contains

Is there a way to automatically adjust the size of a textarea based on its content? Here is the code I am currently using for this purpose: var element = document.getElementById(event.target.id); var content = $(this).val().trim(); if (content == "") { ...

Is it possible for third party packages to function properly without the node_modules directory?

Whenever we push our code to GitHub or any other remote repository service, we make sure to exclude the node_modules folder. This begs the question: how are all the third-party libraries functioning on the hosted website if the node_modules folder is not ...

Using Three.js to create a distorted texture video effect

Check out the example linked here for reference: In this particular project, there are two cylinders involved - an outer cylinder with an image texture and an inner cylinder with a video texture. Once the second cylinder is created and added to the scene, ...

The `Target closed` error in Playwright Library is triggered solely by the closing of either the `context` or `browser`

The code snippet below showcases a Node.js script that leverages the Playwright Library for browser automation (not Playwright Test) to extract data from a local website and display the results in the terminal. The challenge arises when the script encounte ...

Using Angular and nativeElement.style: how to alter cursor appearance when clicked and pressed (down state)

I am working with a native elementRef CODE: this.eleRef.nativeElement.style = "_____?????_____" What should go in "???" in order to apply the :active style to the element? (I want to change the cursor style when the mouse is clicked down, not when it is ...

Tips for showing a limited number of results the first time in an AngularJS application

I am a beginner in AngularJS and Ajax requests. I created a demo where I make an Ajax request to get remote data and display it in a list. My goal is to initially show only 10 results when the page loads for the first time, and then load the next 10 result ...

The issue of excessive recursion in Typescript

Currently, I am in the process of learning Typescript while working on some exercises. While attempting to solve a particular problem, I encountered an error related to excessive recursion. This issue arises even though I created wrapper functions. About ...

Transforming the navigation menu using CSS, HTML, and jQuery

One challenge I am facing involves creating a menu similar to the one on http://edition.cnn.com/. I want the clicked button in the menu to receive focus, while the others lose it. Despite trying various methods, I have not been successful. Can someone off ...

Can a dynamic field name be incorporated into a JavaScript Object?

My goal is to dynamically add a field name and update the value based on that. In my situation, the eventType can have 4 types: delivery, send, open, click. However, when I implement this code, I am only getting the eventType as a string. const event = J ...

Curved lines on canvas

I am currently using the stroke and path features in the canvas to create two lines, with the intention of giving them a curved, wave-like effect. I would like to achieve this without having to create an actual image in Photoshop. Is there anyone who can ...

refusing to display the pop-up in a separate window

Hi there, I'm having an issue with a link that's supposed to open in a pop-up but is instead opening in a new tab. I'd like it to open in a proper pop-up window. <button class="button button1" onclick=" window.open('te ...

Error: Reactjs - Attempting to access the 'name' property of an undefined variable

As I continue to learn about React, I have been experimenting with props in my code. However, I encountered an error where the prop is appearing as undefined. This issue has left me puzzled since I am still at a basic level of understanding React. If anyo ...

Customize the React Material UI Autocomplete with a unique dropdown menu and a convenient Add Button feature located at

Seeking assistance in creating an autocomplete feature in React using Material-ui, with a unique custom dropdown design including a button labeled Add New Element positioned at the bottom. https://i.sstatic.net/6rY99.png Various attempts have been made t ...

Using HTML and JavaScript to add variables into the URL within the window.location

I have been struggling to incorporate longitude and latitude into the URL. Despite researching various topics online, I have not found a solution that works for me. Below is the HTML code that showcases the issue. When you click the "Show Position" button ...

Material Design Autocomplete search feature in Angular 2

I'm encountering some challenges with autocomplete in Angular2 Material Design. Here are the issues I'm facing: 1. When I type a character that matches what I'm searching for, it doesn't display in the autocomplete dropdown as shown in ...