What is the most effective way to organize an array according to a key function that is computationally intensive?

After posting this question regarding sorting an array with a key function, it became evident that utilizing a comparison function was inevitable.

The challenge at hand includes:

  1. Having a resource-intensive key function that needs to be transformed into a comparison function
  2. Dealing with an array of objects, restricting the use of a hash table for memoizing key function results

Below is a demonstration of a sample array and a simple key function:

myArr = [{'foo': 5, 'bar': 'hello'}, {'foo': 3, 'bar': 'world'}];
keyFunc = obj => obj.foo;  // sort by the value of the `foo` attribute

myArr.sort(???);
// expected result: [{'foo': 3, 'bar': 'world'}, {'foo': 5, 'bar': 'hello'}]

Given these constraints, the query remains on how to effectively sort the array?

Answer №1

To ensure that the costly key function is executed only once per element in the array, it is essential to implement memoization. One effective approach is to pair each element with its corresponding key value by creating an array of [key, element] pairs and then sorting them:

myArr = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}];
keyFunc = person => person.age;

// generate keys for each element in the array
keyedArr = myArr.map(person => [keyFunc(person), person]);

// sort the array based on the keys
keyedArr.sort((a, b) => a[0] - b[0])

// extract elements from the keyed array
result = keyedArr.map(pair => pair[1]);
// result: [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]

It's important to note that this method will only be effective if the key function returns a numerical value.

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

Converting time from 00:00:01 to a format of 8 minutes and 49 seconds in Angular

Is there a way to transform a time value from 00:00:01 (not a date object) into a format showing 8 minutes and 49 seconds? Even after consulting the Angular 'date pipe' documentation, I couldn't find a solution to this issue. ...

Can someone explain the distinction between 'return item' and 'return true' when it comes to JavaScript array methods?

Forgive me for any errors in my query, as I am not very experienced in asking questions. I have encountered the following two scenarios :- const comment = comments.find(function (comment) { if (comment.id === 823423) { return t ...

Convert a JSON array with a single element into a valid JavaScript object

Within my programming scripts, I frequently utilize PHP arrays with numeric keys. However, these keys are not necessarily sequential from 0 to n; they can be randomly chosen. Specifically, I am working on a script that organizes scheduled events at specifi ...

Eliminate any properties with values that exceed the specified number in size

:) I'm trying to create a function that removes properties with values greater than a specified number. I've searched through multiple resources like this question on how to remove properties from a JavaScript object and this one on removing pro ...

Embedding Google+ Sharing in an iframe

I'm currently working on a web application that needs to be compatible with PC, tablets, and mobile phones. I'm interested in integrating Google+ Sharing into the app. However, it appears that when using the url , there are issues with blocking ...

Using custom class instances or objects within Angular controllers is a simple process

Using three.js, I have created a class called threeDimView that houses my scene, camera, and other elements. In my JavaScript code, I instantiate a global object of this class named threeDimView_. threeDimView_ = new threeDimView(); Now, I wish to displa ...

The sample Ajax XML code provided by W3Schools is ineffective

While studying xml parsing in ajax on w3schools.com, I came across an example that functioned perfectly online. However, when I saved it to my desktop as abc.html and note.xml, the XML values weren't displaying. Even though the HTML elements were vis ...

Navigating between interfaces without the need to constantly refresh or reload

Currently, I am in the process of developing a website using ASP.NET MVC that allows users to navigate between pages without refreshing each time. My approach involves treating views as 'areas' or mini master pages, utilizing partial views inste ...

Removing an Element According to Screen Size: A Step-by-Step Guide

Currently, I am facing a dilemma with two forms that need to share the same IDs. One form is designed for mobile viewing while the other is for all other devices. Despite using media queries and display: none to toggle their visibility, both forms are stil ...

"Request sent through Ajax can only be accepted by Localhost and specified IPs

Having an issue with my ajax post request. I want to post to a specific URL, but I also want it to accept both "localhost" and the IP address in the browser. If I set it up like this: $.ajax({ url: 'http://192.168.9.30/test/suma.php&ap ...

What is the proper way to place a newly added element using absolute positioning?

Currently, I am in the process of developing a tooltip feature. This function involves adding a div with tooltip text inside it to the element that is clicked. However, I am facing a challenge in positioning this element above the clicked element every tim ...

Replacing JS/CSS include sections, the distinction between Debug and Release versions

Can you share how you manage conditional markup in your masterpages for release and debug builds? I am currently using the .Net version of YUI compress to combine multiple css and js files into a single site.css and site.js. One idea I had was to use a u ...

Extracting over 100 tweets from the Twitter API with the help of Node.js

I am facing a challenge while trying to fetch over 100 tweets from Twitter in nodejs as I continuously receive an empty array. Here is the approach I have attempted: const MAX_TWEETS = 200; const TWEETS_PER_REQUEST = 100; async function retrieveTweets(T, ...

Ways to display or conceal multiple div elements using JavaScript

A group of colleagues and I are currently collaborating on a project to create a website showcasing our research. We have incorporated 1 page that contains detailed descriptions of six different subjects: system biology, proteomics, genomics, transcripto ...

What is the best way to create a promise in a basic redux action creator?

My function add does not return any promises to the caller. Here's an example: let add = (foo) => {this.props.save(foo)}; In another part of my application, I want to wait for add() to finish before moving on to something else. However, I know t ...

Using C# Razor Pages to send checkbox values via AJAX requests

In my model class, I have the following: public class DataModel { public bool Display { get; set; } } After deserializing a FormData object to a JSON object, I am posting the value from a checkbox like this: this.FormToJSON = form => { const ...

Error: An issue occurred in the driver.execute_script function causing a JavascriptException. The error message indicates

When attempting to run some JavaScript code on the Chrome driver, I encountered a JavascriptException. Despite my confidence in the correctness of the JS code, the following error message was displayed: raise exception_class(message, screen, stacktrace) s ...

Is it possible to simultaneously employ two asynchronous functions while handling two separate .json files?

Is it possible to work with 2 .json files simultaneously? My attempt did not succeed, so I am looking for an alternative method. If you have a suggestion or know the correct syntax to make this work, please share. And most importantly, does the second .j ...

What to do when VueJs computed method throws an error: "Cannot access property 'words' of undefined"?

Here is some pseudo code that I've written: var vm = new Vue({ el: '#test', data: { words: [{name:'1'}, {name:'2'}, {name:'3'},{name:'4'},{name:'5'},{name:'6'}], } ...

The button in my form, created using React, continuously causes the page to refresh

I tried to create a chat application using node.js and react.js. However, I'm facing an issue where clicking the button on my page refreshes the entire page. As a beginner in web development, please forgive me if this is an obvious problem. You can fi ...