Sort the array by unique ID and retrieve the object with the first and last index

I am working with an array that looks like this:

[{
    "res": [ '123', 'One', '20210318' ]
}, {
    "res": [ '123', 'One', '20210319' ]
}, {
    "res": [ '123', 'One', '20210320' ]
}, {
    "res"': [ '123', 'One', '20210321' ]
},{
    "res"': [ '456', 'Two', '20210401' ]
},{
    "res"": [ '456', 'Two', '20210402' ]
},{
    "res": [ '456', 'Two', '20210403' ]
},{
    "res": [ '456', 'Two', '20210404' ]
}]

My goal is to extract the following unique values from the array:

[{ 
    "res": [ '123', 'One', '20210318' ]
 }, {
    "res": [ '123", "One", "20210321' ]
 },{
    "res": [ '456', 'Two', '20210401' ]
    },{
    "res": [ '456', 'Two', '20210404' ]
}]

This means finding the first occurrence of unique value "20210318" for "One" and the last index unique value "20210321", and for "Two" finding the first unique value as "20210401" and the last index unique value as "20210404"

So far, I have successfully filtered the array by their unique IDs and obtained only two results - the first unique occurrence of "One" and the first unique occurrence of "Two"

  const getFilteredArray = array.filter((v,i,a)=> {

    const getFilter = a.findIndex( t => {
      return t.res[0] === v.res[0]
    }) === i;

    return getFilter;
  })

Answer №1

Here lies a potential solution, perhaps not the optimal one.

let groupedData = array.reduce((acc, {result: [key1, key2, value]}) => {
    acc[key2] = acc[key2] || {};
    acc[key2].key1 = key1;
    if (acc[key2].min == null || acc[key2].min > value) acc[key2].min = value;
    if (acc[key2].max == null || acc[key2].max < value) acc[key2].max = value;
    return acc;
}, {});
Object.keys(groupedData).reduce((acc, k) => {
    const val = groupedData[k];
    acc.push({result: [val.key1, k, val.min]});
    acc.push({result: [val.key1, k, val.max]});
    return acc;
}, []);

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

The behavior of the Ionic checkbox in version 5 seems to be quite delayed

I am facing an issue with binding the checked attribute value on an ion-checkbox, as the behavior seems to be delayed. In my .ts file, I have an array variable named user_id. In my checkbox list, I am trying to populate this array based on which checkboxe ...

JavaScript does not allow executing methods on imported arrays and maps

In my coding project, I created a map named queue in FILE 1. This map was fully built up with values and keys within FILE 1, and then exported to FILE 2 using module.exports.queue = (queue). Here is the code from FILE 1: let queue = new.Map() let key = &q ...

Retrieve information from arrays within objects in a nested structure

I am working with structured data that looks like the example below: const arr = [{ id: 0, name: 'Biomes', icon: 'mdi-image-filter-hdr', isParent: true, children: [{ id: 1, name: 'Redwood forest& ...

Adding the unzip feature is not within my capabilities

I am a novice Japanese web developer. Unfortunately, my English skills are not great. I apologize for any inconvenience. I am interested in utilizing this specific module: https://www.npmjs.com/package/unzip To do so, I executed the following commands ...

Struggling with replacing text in an array using Javascript (Angular)

I am facing an issue where I need to remove the 'hello' substring from each object field in my objects array. However, I keep getting an error message saying "Cannot read property 'indexOf' of null". This error is occurring because I am ...

Steps to fix ESlint warning: Avoid using assignment in return Statement (no-return-assign)

In my React application, I am utilizing the package found at https://github.com/appleboy/react-recaptcha to create a Recaptcha component. Below is an image of what the component looks like, along with an eslint warning: https://i.sstatic.net/ZleMK.png Th ...

Auto-scrolling text box cursor movement

My query is quite similar to the topic discussed in this thread on automatic newline in textarea. However, my situation involves multiple textareas with a 1-row attribute, making it seem like writing on air due to the absence of visible borders (I've ...

Using a looping mechanism to store strings in a list, followed by outputting the contents of the

I have created a program that prompts the user to input multiple strings in a loop. The loop should break when the user enters "stop" and then print out all the entered strings with a comma after each word. For instance, if the user inputs "first", "second ...

Troubleshooting problem with Angular Click Outside Directive and unexpected extra click event issue

The challenge I'm facing involves implementing a custom Click Outside Directive for closing modal dialogs, notifications, popovers, and other 'popups' triggered by various actions. One specific issue is that when using the directive with pop ...

Is the jQuery ajax .done() function being triggered prematurely?

Struggling with a problem here. I'm dealing with this code (simplified): var initializeZasilkovna = function () { // Initialize object window.packetery.initialize(); }; // Check if the object doesn't exist if (!window.packetery) { // It ...

What is the best way to enhance a React Native component's properties with Flow?

I'm currently working with Flow version 0.54.1 in my React Native project, specifically using version 0.48.3. I have developed a component named PrimaryButton that acts as a wrapper for the native TouchableOpacity component. My goal is to define custo ...

Incorporate a progress bar into the Material-UI table design

I have the following example of a Material-UI table: import React from "react"; import clsx from "clsx"; import { createStyles, lighten, makeStyles, Theme } from "@material-ui/core/styles"; import Table from "@mat ...

Tips for transferring a variable from a webpage's JavaScript to Node.js

Having an issue with transferring a Javascript variable to node js for JSON file storage. The data doesn't seem to be writing to the file, possibly due to an error in the AJAX Post request or the node JS routing. The javascript is executed on an HTML ...

Differentiating onClick events for parent and child elements

I need help with my JSX code: <div id="parent" onClick={clickOnParent} style={{ width: 100, height: 100 }}> <div id="child" onClick={clickOnChild} style={{ width: 20, height: 20 }} /> </div> When I click on the pare ...

Setting an action when clicking on a slice of a Doughnut chart using Chart.js

I have been working on integrating chart.js into my Django Project, and so far it has been going smoothly. I successfully created a doughnut chart with two slices. Now, I am trying to implement separate actions for each slice when clicked, such as redirect ...

Tips on scrolling the web page until the desired web element is visible and carrying out necessary tasks

When searching for input, multiple table data is retrieved. A "show as text link" is present in different table rows that needs to be clicked. I wrote a code that works fine in IE on one machine but does not work on a different machine due to variations i ...

Allow Vue to handle the registration of the datepicker event

Is there a way to notify Vue when the datepicker changes the selected date? new Vue({ el: '#app', data: { termin: '' }, computed: { }, methods: { } }) This is just an input field: <div id="app"> <div c ...

Observables and the categorization of response data

Understanding Observables can be a bit tricky for me at times, leading to some confusion. Let's say we are subscribing to getData in order to retrieve JSON data asynchronously: this.getData(id) .subscribe(res => { console.log(data.ite ...

Incorporate an array in PHP and employ jQuery's 'get' method

I am attempting to query the database in PHP and retrieve a "toplist" that is limited to 10 results. My goal is to create an array and send it back to Jquery using $.get(). However, I am facing issues with receiving all the data with this code. How can I ...

Tips on making the form validation script operational

After developing a form alongside a form validation script to ensure that all fields are completed, the name and city sections only contain letters, while the age and phone sections solely include numbers, issues have arisen. It seems that despite the cons ...