Enhance the efficiency of traversing a lengthy list of comparisons within an array.filter method

I am struggling with finding an efficient method to filter out items from an array of objects based on two specific attributes matching those of the last 6 items of another array. Currently, I have a manual process in place which results in cumbersome and lengthy code:

const filteredList = list.filter(x => {
  return (
    (x.someProperty === parseInt(anotherList[anotherList.length - 1][0].someProperty, 10) && x.anotherProperty === anotherList[anotherList.length - 1][0].anotherProperty) ||
    (x.someProperty === parseInt(anotherList[anotherList.length - 2][0].someProperty, 10) && x.anotherProperty === anotherList[anotherList.length - 2][0].anotherProperty) ||
    (x.someProperty === parseInt(anotherList[anotherList.length - 3][0].someProperty, 10) && x.anotherProperty === anotherList[anotherList.length - 3][0].anotherProperty) ||
    //remaining comparisons for each of the last 6 items
  )
}

Although this approach currently functions as intended, I am interested in exploring a more optimal solution that does not require explicitly listing and comparing each item of anotherList. Is there a better way to achieve this filtering process?

Thank you.

Answer №1

To compare the last six items with the provided values, you can try this approach.

const filteredList = list.filter(x =>
    anotherList
        .slice(-6)
        .some(item =>
            x.someProperty === Math.floor(item[0].someProperty) &&
            x.anotherProperty === Math.floor(item[0].anotherProperty)));

A more concise method using an array to store the keys.

const filteredList = list.filter(x =>
    anotherList
        .slice(-6)
        .some(item =>
            ['someProperty', 'anotherProperty'].every(k =>
                x[k] === Math.floor(item[0][k]))));

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

Looking to send information to a different website and get the response back using JavaScript?

Seeking assistance: I'm attempting to post my University seat number, 1da07cs102, to http://results.vtu.ac.in/results.php. This website uses rid as a name in form. How can I use JavaScript to retrieve my results from the specified site and display the ...

Is there a way to prevent undefined properties when using .each in jQuery with a JSON object?

I am trying to populate the values of <inputs> on a webpage using data from a JSON object. http://codepen.io/jimmykup/pen/exAip?editors=101 To begin, I create a JSON object with two values - one for name and one for url. var jsonObj = []; var nam ...

Enhance Your GoJS Pipeline Visualization with TextBlocks

I am facing challenges in customizing the GoJS Pipes example to include text within the "pipes" without disrupting the layout. Although I referred to an older response on the same query here, it seems outdated or not detailed enough for me to implement wit ...

Utilizing the 'PUT' update technique within $resource

Hey there, I'm pretty new to Angular and looking for some guidance on how to implement a PUT update using angular $resource. I've been able to figure it out for all 'jobs' and one 'job', but I could use some assistance with in ...

What is the method for placing one object within another object?

This is a sample of my data collection: [ { "column1":"data1", "column2":"data2", "column3":[ { "column31":"data31", "column32& ...

Are there any libraries available that can assist with managing forms similar to how Google Contacts handles them

By default, Google Contacts has a feature where the form displays values with some of them being read only. However, when you click on a value, it converts the field into an editable form so you can easily make changes. After editing and pressing enter, th ...

Here are some tips for retrieving information from a JavaScript object

My goal is to extract the values of free_time, done_ratio, criticalTask, and dependency from a JavaScript object for each task. I attempted to achieve this, but unfortunately, it didn't yield the desired results. var mock_data_allocation = {"alloc ...

The offset value was inconsistent in the desktop version of Firefox

Could you take a look at my code on the fiddle link, Here is the code snippet: <body> <div id="content" style="width:400px; height:110px;"> <svg id="circle" height="300" width="300"> <circle cx="150" cy="150" r="40" st ...

Methods for adding a line to an array

I am currently working on a loop where I need to populate my array called photos: $scope.photos = []; var str = data.data.Photos; var res = str.split('|'); angular.forEach(res, function (item) { ...

Operating on a duplicate of the array is necessary for mapping an array of objects to function properly

I'm starting to uncover a mysterious aspect of Javascript that has eluded me thus far. Recently, I've been pulling an array of objects from a database using Sequelize. This array is quite intricate, with several associations included. Here' ...

Why isn't my textarea in jQUERY updating as I type?

On my website, I have a comment script that is not functioning correctly in some parts of the jQuery/JavaScript code. Instead of posting an edited comment to PHP, I created a notification window to test if the value passed through is actually changing. W ...

Remove the Prisma self-referencing relationship (one-to-many)

I'm working with this particular prisma schema: model Directory { id String @id @default(cuid()) name String? parentDirectoryId String? userId String parentDirectory Directory? @relation("p ...

Angular utilizes ZoneAwarePromise rather than a plain String output

I expected the giver code to return a string, but it is returning ZoneAwarePromise. Within the service: getCoveredPeriod() { let loanDetails = this.getLoanDetails().toPromise(); loanDetails.then((res: any) => { const coveredPeriodStart ...

Are there any alternatives to jQuery address in the realm of dojo?

Currently, I am working on developing an ajax application using dojo. I am curious if there is a feature comparable to jQuery Address in terms of functionality. My goal is to implement ajax-based hash url navigation similar to Twitter and Facebook using do ...

How to access a specific key in a JSON string using square brackets in PHP

My current challenge involves dealing with an array: [{"title":" \ud83c\uddfa\ud83c\udde6 \u041b\u0443\u0447\u0448\u0435\u0435 \u043a\u0430\u0437\u0438\u043d\u04 ...

Steps for importing jQuery typings into TypeScript:1. First, install the jQuery

I've searched for similar questions, but haven't found one that matches my issue. Can someone help me figure out what to do next? In my Visual Studio project, I used package.json to download jquery typings into the node_modules folder: { "ver ...

What is the reason behind Angular generating files with 'es5' and 'es2015' extensions instead of 'es6' (or no extension)?

Recently, I installed the Angular CLI (@angular/cli 9.0.1). My goal was to create a new Angular Element, package it, and then integrate it into another application. Following several blog tutorials, I found that they all mentioned the final step of creati ...

Why is the "class" attribute of an SVG node not being applied when I change it?

I am having trouble changing the "class" attribute of a node in SVG using my AngularJS Directive. Even though I've written the code to do so, it doesn't seem to be applied properly. This is the code snippet from my Directive: node = node.data(f ...

elevate the div with a floating effect

My goal is to create a chat feature for users that will only be visible for a limited time period. I was thinking of using PHP and timestamp to achieve this functionality, but I also want to make the chat visually disappear by having the message div float ...

I need to prevent form submission when the submit button is clicked. How can I achieve this?

I'm currently developing a web application using ASP.net. Within the form, there is a submit button that has the following code: <input type='submit' value='submit request' onclick='btnClick();'>. The desired func ...