Extract the Top X elements from a multidimensional array

Consider an Array that consists of nested arrays:

[
["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a9a8abe091b6bcb0b8bdffb2bebc">[email protected]</a>", 1, 9, 338],
["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="740c0d0e46340d151c1b1b5a171b19">[email protected]</a>", 1, 2, 159],
["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94ecedeea7d4edf5fcfbfbbaf7fbf9">[email protected]</a>", 1, 5, 462],
["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="196160632d596078717676377a7674">[email protected]</a>", 1, 6, 417],
["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f8808182cdb89f95999194d69b9795">[email protected]</a>", 1, 3, 156],
["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa828380ccba9d979b9396d4999597">[email protected]</a>", 1, 8, 414],
]

We aim to extract the top 2 based on the last column:

["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f28a8b88c1b28b939a9d9ddc919d9f">[email protected]</a>", 1, 8, 462],
["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e199989bd5a19880898e8ecf828e8c">[email protected]</a>", 1, 6, 417],

We can utilize Array.filter, although implementing it in this scenario may pose a challenge.

Answer №1

To retrieve the top two elements, you can sort in descending order based on the value at index 4 and select the first two elements.

This suggestion involves using destructuring assignment, where an array is deconstructed and the property 4 is extracted and assigned to variables a and b.

Example:

                                                  vvv
{ 4: a } = ["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="651d1c1f54250208040c094b06016e2121699b06aa">[email protected]</a>", 1, 9, 338]
  ^

Result

a = 338

var array = [["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="730b0a094233141e121a1f5d101c1ed80c71caad0771afceef54cc7faacabeab26ea2c7facaebaeefa56ecaba8daaceaacbbcd128361fd13d62be10ba42536f79acf08577638"], 1, 5, 462], ["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="335b5a59635c53534557595602525a35093452595c43585600375b53353b564540553447115158085381"], 1, 3, 156], ["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="573f3e3d67127b2a77a1b65e72fb92797e78798254797bad90747708707e19927385f286ec9a06708cb93afc76cab96dedadd86eff78192f87191a786838296485a89570773846e140415344c468276858b84468b81878971859a7058db329e998c4bcd98"], 1, 8, 414]],
    top2 = array.sort(({ 4: a }, { 4: b }) => b - a).slice(0, 2);

console.log(top2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Unsorted version:

 function findTopTwoValues(arr){
    let topOne = {4: - Infinity}, topTwo = { 4: - Infinity};
    for(const value of arr){
        if(value[4] > topOne[4]){
            topTwo = topOne;
            topOne = value;
        } else if(value[4]> topTwo[4]){
           topTwo = value;
        }
    }
    return [topOne, topTwo];
}

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

How to create a clickable link using Vuetify's v-btn component

As a newcomer to vue and vuetify, I would greatly appreciate some explanation and examples. My goal is to create a button that directs users to an external site, like youtube.com. Below is the code I currently have, but unfortunately it's not function ...

Methods for determining the disparity in days between two dates and the ratio of days yet to come

Within my React project, I am in need of a functionality that calculates the number of days remaining between two specific dates. Essentially, I want to determine how many days are left from today until the expiration date, and then calculate the percentag ...

Guide on setting up and customizing run.json within the latest JetBrains Fleet for Next.js

I've been attempting to set up input/output for the latest IDE from JetBrains, Fleet. However, I've hit a roadblock and can't seem to figure it out on my own. That's why I'm turning to the Stack Overflow community for help - how do ...

Updating the video tag's source attribute using JSON information

I am in the process of creating a unique video player using HTML and Javascript that will sequentially play a set of videos until all 6 have been displayed. The URLs for these videos are stored within an array that is mapped in a .json file named clips.jso ...

Deciphering intricate JSON structures using PHP

In my current situation, I am receiving a server response with mixed data and now I need to handle it using PHP. Array ( [14424174] => Array ( [0] => Array ( [id] => 45 ...

How does AngularJS watcher behave when a callback is triggered during a reload or router change?

Can anyone explain why the watch callback is triggered upon browser reload or Angular route change even when the old value and new value are the same? Here's an example: $scope.test = "blah"; $scope.watch("test", function(new, old){ console.log(ne ...

Minimize a pop-up window and navigate to a different webpage

I have created a login/logout form that includes the option to delete my account. When I click the "Sterge cont" button, a pop-up window appears asking if I truly want to delete the account. If I select "NU," the account will not be deleted and the window ...

Harness the power of $compile within the Angular link function while also retrieving and utilizing the arguments of the

I am currently developing a custom directive in angular.js 1.x Here is how I call the directive: <mydirective dirarg={{value-1}}></mydirective> My goal is to define the directive by including code to alter the DOM within the directive's ...

A step-by-step guide on leveraging useRef() to specifically target dynamic material-ui tabs

When attempting to upload files to a specific channel, they always end up being uploaded to the first tab or channel. I've been using useRef to try and fix this issue, but I'm not sure what exactly is missing. By "tab," I am referring to the tab ...

Firefox displays an error when using jQuery.load(), but Chrome functions properly without any issues

I have created a function that opens a page in a dialog box instead of the main window. The code has been cleaned up and here is the revised version: var baseUrl = window.location.origin + '/static/docs/'; function handleLinkClick(event) { ev ...

Creating a personalized message for a failed "Get" request using the HTTPS native module in combination with

Currently, I have implemented an Express application that includes an HTTP GET request to an external API. It functions properly when there are no errors; however, I am looking to customize the response sent to the client-side in case of failures: const ht ...

The button labeled "modify layout" remains unresponsive when activated

Allow me to start by saying that I am not a coding expert. Currently, I am enrolled in a computer science class and have a basic understanding of HTML, CSS, and some Javascript. However, I have encountered a problem that I cannot solve. When I click on th ...

Welcome to Digital Ocean! It appears you are attempting to utilize TypeScript

Over the past 48 hours, I've been struggling to build my project on a DO App. Strangely enough, there were no changes made to the project, yet out of nowhere it started breaking with an unexpected error message: [2023-04-06 09:03:02] │ It seems like ...

Customizing the design of vuetify table header to your liking

My goal is to implement a custom style for v-data table headers using the fixHeader method. The CSS code is intended to keep the header fixed in place even when scrolling horizontally. The issue arises as the style is applied to the inner <span> ele ...

Tips for generating a new method using an existing one

Searching for the best practice to inform the ts compiler that a method will be generated at runtime. interface Todo { /* ... */ } export class TodoModel { todos: Todo[] = []; constructor() { //... } bindTodoListChanged(callback : (todos: Todo[]) ...

Tips for properly modifying an attribute within an array of objects in JavaScript using ReactJS

My array of objects looks like this: this.state = { itemSquare: [{ item: "bomb", status: false }, { item: "bomb", status: false }, { item: "bomb", status: false }, { item: "bomb", status: ...

jQuery: Function is not running as expected

I'm facing a challenge in executing a function twice, and I'm having trouble identifying the issue. Check out my JSFiddle at the following link: http://jsfiddle.net/g6PLu/3/ Javascript function truncate() { $(this).addClass('closed&apo ...

Tips for updating a URL using data obtained from a JSON response

As I loop through an array from JSON, I extract all the necessary information. For example, if I have cards for blog posts that include the title, short description, published date, and URL. When clicking on a card, it redirects to a corresponding page ba ...

Merge arrays together and organize them in ascending order

I am currently attempting to concatenate two integer arrays and then sort the resulting array. The input part works correctly, but I suspect there may be issues with the concatenation process. Any guidance on improving this would be greatly appreciated. ...

How can one retrieve data from two distinct API routes within a Next.js application?

Currently, I am working with Next.js and facing a challenge in fetching data from two different API routes simultaneously. My intention is to retrieve this data within the getServerSideProps function. The first dataset that I require can be found at the e ...