methods for efficient set computations

I have a collection of sets in the format (a,b) which are as follows:

(2,4) (1,3) (4,5) (1,2)

If I am given a pair like <2,1>, I want to identify all sets in the collection where 2 or 1 is the first element. In this case, it would be (2,4), (1,3), and (1,2) and then determine the maximum value for the second element, so here it would be 4.

What is the most efficient way to achieve this?

My initial approach was to extract all 'a' values from the sets, intersect them with <2,1>, and then find the max value of 'b'. However, this method may not perform well with larger datasets. Additionally, we can consider restructuring the data or performing preprocessing if necessary.

I am using plain JavaScript, and my data is stored as arrays of tuples or objects with two integer properties.

Thank you for any suggestions!

Answer №1

Explore two simple methods, one utilizing a for loop and the other employing reduce.

function findMaxValue (array, filter) {
   let maxValue = 0; 
   for (let [key,value] of array) {
        if (filter.includes(key))
            maxValue = Math.max(maxValue, value)
   }
   return maxValue;
}

function findMaxValue2 (list, filter) {
     const getMax = (max,[key,value]) => Math.max(filter.includes(key) * value, max);
     return list.reduce(getMax, 0);
}

const info = [
  [2, 4],
  [1, 3],
  [4, 5],
  [1, 2]
]

const filtering = [1, 2];

console.log(findMaxValue(info, filtering))
console.log(findMaxValue2(info, filtering))

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 with Vue component not updating Vuex state before it loads?

At times, the token is committed to Vuex store while other times it is not. userLogin() { axios.post('api/login', this.logindata,) .then(response => { let token = JSON.parse(localStorage.getItem('token')); t ...

AngularStrap's bs-modal is failing to display content

I have a question, here is a Plunker with the code: http://plnkr.co/edit/SNFy2XcOBefUavG1QCqD?p=preview <button class="btn btn-default" data-template="customer.tpl.html" bs-modal="modal">New Customer </button> < ...

Arranging a Django queryset according to a separate list containing IDs and corresponding scores

I'm currently faced with a mental block on what seems like a simple task initially. My objective is to retrieve a list of ids for selection and scores to use for sorting. Here is my current approach: ids = [1, 2, 3, 4, 5] items = Item.objects.filt ...

Having trouble with Javascript in getting one-page scroll navigation to work?

Hey there, I am working on creating a one-page scroll navigation with some basic javascript to add a smooth animation effect that takes 1 second as it scrolls to the desired section. However, I seem to be experiencing an issue where it's not functioni ...

What is the syntax for creating a for loop in JSX within a React component?

I am working on a simple program that involves using a for loop to print numbers from 0 to 10. My goal is to utilize a for loop to print these numbers and pass the props to a child component. Please see my code below: import React, { Component } from &apo ...

I am not enhancing the array's value; rather, I am substituting it

Hey everyone, I'm currently working on extracting an array of Sizes and Colors from an object. The goal is to trigger a handler, clickHandler(), when the input is clicked. However, each time the handler is invoked, the code ends up replacing the value ...

Encountering an issue with Masonry's container.append that is causing an Uncaught TypeError: Object does not possess the filter method

I have implemented infinite scroll on my website to display images. The images are arranged using a tool called masonry. Initially, I only load 10 images into the #container div when the page loads. These images are aligned perfectly with no errors in the ...

How to retrieve the path, route, or namespace of the current or parent component/view in a Vue.js application

I have been working on enhancing a sub-menu system for vue.js that dynamically populates based on the children routes of the current route. I recently asked a question about this and received a helpful answer. Currently, I am trying to further improve the ...

What is the best way to create this server backend route?

I'm currently working on a fullstack project that requires a specific sequence of events to take place: When a user submits an event: A request is sent to the backend server The server then initiates a function for processing This function should ru ...

"Executing a query on Angular Firestore using the where clause fetches all documents from the

I am encountering a perplexing issue with my angular app that is connected to Firestore. Despite following the documentation closely, when I query for documents in a collection based on a specific condition, the array returned contains every single documen ...

Having trouble showing the information in JavaScript

Here is some code snippet: if(data.error) { msg1.textContent=data.error } else { msg1.textContent=data.location msg2.textContent=data.forecast console.log(data.forecast) } }) Unfortunately, I'm facing an is ...

The debate: Switching off Next.js SSG - Harness or Constant?

Currently experimenting with different methods to disable NextJS SSG. The following custom hook implementation is functional: import { useState, useEffect } from "react"; const useClientCheck = () => { const [isClient, isClient ...

Transform JavaScript AJAX to HttpWebRequest implementation code

Is it possible to mimic an AJAX call to a web service within a console application using HttpWebRequest? Here is the source request: var webRequest = Sys.Net.WebServiceProxy.invoke('', 'MyMethod', false, {p1:aa,p2:bb,p3:123}, onSucc ...

Instructions for incorporating a personalized document in NextJs version 13

In order to enhance the design of my upcoming Next.js 13 project, I am looking to integrate a custom design system package. This particular package necessitates the creation of custom documents within the page directory, as outlined in the official Next. ...

The casperjs evaluate function isn't able to provide me with the necessary data I

Having trouble getting my function to return data correctly. I am trying to retrieve the value of this input box. <input type="text" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b6e736a667b6764646025686466">[em ...

An unusual outcome occurred while attempting to duplicate the text

After copying the letter A, I noticed that an empty string is being logged to the console instead of the expected A. However, when I paste, the console does successfully log the letter A. document.addEventListener('copy', handler); document ...

Flask app facing compatibility issues with jQuery .getJSON

I am encountering an issue with my flask application where I am attempting to send JSON data to the browser and render it. However, the line containing $.getJSON() is not executing as expected. Here is a breakdown of the relevant code: app.py from flask ...

Determine the item in a collection of objects that contains a specific key

What is the most efficient method for locating an object by a specific key in JS when given an array of objects? Utilizing jQuery and underscoreJS is acceptable. I am simply seeking the simplest solution with minimal code. Illustration: Suppose we have a ...

Turn off the whole DIV container and its contents once the button is clicked

Here's an example of the HTML markup: <div id="picing-selection" class="disableMe"> <a class="upgradeSub" value="@ViewBag.Id"> Upgrade <i class="fa fa-money"></i> </a> </div> The onclick event is d ...

Comparing defaultProps with the logical OR operator

Being relatively new to react, I’ve adopted a method of defining default values which looks like this: class TextInput extends Component { render() { return ( <input type="text" name={ this.pr ...