Working with Typescript to map and sort the key values of a new datasource object

Managing a large datasource filled with objects can be challenging. My goal is to rearrange the order of objects in the array based on new values for each key. Whenever a new value for a key is found, I want the corresponding object to move to the top of the array. This way, the top elements in the array will always represent the different values that properties can have.

arr[0] = {name: john, age: 14, address: xxx}
arr[1] = {name: john, age: 14, address: xxx}
arr[2] = {name: marie, age: 14, address: xxx}
arr[3] = {name: marie, age: 14, address: xxx}
arr[4] = {name: john, age: 15, address: xxx}

The desired outcome would look like this:

arr[0] = {name: john, age: 14, address: xxx}
arr[1] = {name: marie, age: 14, address: xxx}
arr[2] = {name: john, age: 15, address: xxx}
arr[3] = {name: marie, age: 14, address: xxx}
arr[4] = {name: john, age: 14, address: xxx}

This example is simplified as the actual dataset may vary in keys, quantity, and values. To dynamically achieve this reordering, I am currently iterating through all objects, identifying new values for each key, storing them in an array of unique values, and moving the current object to the top of the array based on these new values. The process repeats for each object containing a new key value.

filterDS(dataSource){

    let uniqueColumns;
    let i = 0;
    let j = 0;
    let temp;
    dataSource.forEach(data => {
      let keys = Object.keys(data);
      keys.forEach( key => {
        console.log(key + ":" + data[key]);
        uniqueColumns[key].push(data[key]);
        temp = dataSource[i];
        j = dataSource.indexOf(data);
        dataSource[i] = dataSource[j];
        dataSource[j] = temp;
        i++
      })
    });
    return dataSource;
  }

However, I seem to encounter issues when trying to read undefined values. I have attempted to check for empty datasource, key values, and even the current object, but the problem persists. It seems to break when encountering an undefined or empty field. I am unsure of what mistake I might be making here.

Answer №1

To move ahead, consider grouping by the name initially and then looping through the longest group to access each other grouped array by index.

const arr = [{ name: 'john', age: 14, adress: 'xxx' }, { name: 'john', age: 14, adress: 'xxx' }, { name: 'marie', age: 14, adress: 'xxx' }, { name: 'marie', age: 14, adress: 'xxx' }, { name: 'john', age: 15, adress: 'xxx' }, { name: 'tim', age: 15, adress: 'xxx' },];

// Grouping by object.name
const tempMap = {};
for (const o of arr) {
  (tempMap[o.name] ??= []).push(o);
}
const groups = Object.values(tempMap);

// Finding the length of the longest grouped array
const maxLen = Math.max(...groups.map(o => o.length))

const result = [];
// Looping through the longest array to access each grouped array by index
for (let i = 0; i < maxLen; i++) {
  for (const arr of groups) {
    if (i < arr.length) {
      result.push(arr[i]);
    }
  }
}

console.log(result);

Alternatively, create a more generic function that takes a callback to specify the property/ies to group by and an optional sorting function for arranging the grouped arrays before mapping to the result.

function filterDS(dataSource, getProp, sortFn) {
  // Use the provided callback to group-by
  const tempMap = {};
  for (const o of dataSource) {
    (tempMap[getProp(o)] ??= []).push(o);
  }
  const groups = Object.values(tempMap);

  // Sort the groups if a custom sort function is provided
  if (typeof sortFn === 'function') {
    groups.sort(sortFn);
  }

  // Find the length of the longest grouped array
  const maxLen = Math.max(...groups.map(o => o.length))

  const result = [];
  // Iterate through the longest array while accessing each grouped array by index
  for (let i = 0; i < maxLen; i++) {
    for (const arr of groups) {
      if (i < arr.length) {
        result.push(arr[i]);
      }
    }
  }

  return result
}

const arr = [{ name: 'beth', age: 14, adress: 'xxx' }, { name: 'andrew', age: 14, adress: 'xxx' }, { name: 'carrie', age: 14, adress: 'xxx' }, { name: 'xeno', age: 15, adress: 'xxx' }, { name: 'carrie', age: 14, adress: 'xxx' }, { name: 'andrew', age: 15, adress: 'xxx' }, { name: 'andrew', age: 15, adress: 'xxx' },];

console.log(filterDS(arr, (o) => o.name, (a, b) => a[0].name.localeCompare(b[0].name))); // Sorted alphabetically ascending
console.log(filterDS(arr, (o) => o.name)); // Not sorted

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

implementing ng-grid to showcase json information within an angularjs application

Recently I started learning Angularjs and I am looking to showcase the JSON data retrieved from a webservice response in a grid format using ng-grid. Here is my code snippet: function TestController($scope, $http) { alert("test"); $http({ url: &apos ...

Angular 2: Utilizing Http Subscribe Method with "this" Context Pointer

Question: http.request('js/app/config/config.json').subscribe(data => { this.url = data.json().url; }); It seems that "this" is pointing to Subscriber instead of the parent class. I was under the impression that the fat- ...

Transfer the imageURI to a different HTML page

My mobile app, created using PhoneGap, allows users to select an image from their album. I want to pass that selected image and display it on another HTML page. Does anyone have any suggestions on how to achieve this? Below is the code snippet: selectImag ...

Electron's Express.js server waits for MongoDB to be ready before executing queries

As I work on a demo application, Express serves some React code that interacts with a MongoDB database hosted on mLab. The data is retrieved using SuperAgent calls in my main React code loaded via index.html. While everything works fine when starting the ...

What is the best way to iterate through array elements with AngularJS?

I am looking to showcase array values using the ng-repeat directive, and then call the getimage function with itemid and photoidlist in order to retrieve the image URL. The JSON data that I have is as follows: $scope.productslist = { "json": { "re ...

Guide to setting up .env Variables on a DigitalOcean Ubuntu droplet

After deploying my Node.js app on a DigitalOcean Ubuntu droplet, I encountered the need for variables from my .env file. How can I go about creating these variables within the DigitalOcean droplet? ...

Encountering the "No injector found for element argument to getTestability" error while navigating between various single page applications

Currently, I am conducting tests on Protractor for a website that is bootstrapping AngularJS manually. Despite the steps continuing to execute, I encounter this error: Error while waiting for Protractor to sync with the page: "[ng:test] no injector found ...

Building a dynamic cities dropdown menu in ReactJs based on the chosen country

I have an array called countryList that looks like this: export const countryList = [ {name: 'Singapore', code: 'SG', cities:[ "Ang Mo Kio New Town", "Ayer Raja New Town", ...

New options for outdated Webpack i18n plugin and loader

I am currently working on a TypeScript project that requires loading translations from individual .json files assigned to each country. For instance, we would have separate language files like en.json, es.json. The goal is to be able to access these trans ...

Tips for retrieving information from an API and displaying it in a table

I'm struggling to retrieve data (an array of objects) from an API using a Token and display them in a table using Material-UI. However, I keep encountering the following error: Uncaught (in promise) SyntaxError: Unexpected token 'A', "Access ...

What is the best way to detect the presence of the special characters "<" or ">" in a user input using JavaScript?

Looking to identify the presence of < or > in user input using JavaScript. Anyone have a suggestion for the regular expression to use? The current regex is not functioning as expected. var spclChar=/^[<>]$/; if(searchCriteria.firstNa ...

What is the reason behind the continual change in the background image on this website?

Can you explain the functionality of this background image? You can find the website here: ...

Can you explain how this promise functions within the context of the mutation observer, even without an argument?

Recently, I came across a mutation observer in some TypeScript code that has left me puzzled. This particular implementation of a promise within the mutation observer seems unconventional to me: const observer = new MutationObserver((mutations: MutationR ...

Icon not displaying in Firebase background service worker notifications with JavaScript

Although my firebase-messaging-sw.js is functioning properly in displaying background notifications, I have encountered an issue where the icon does not show up even though notification.title and notification.click_action are working correctly. Here is th ...

The Express/Mongoose route consistently modifies the identical item

I'm encountering an issue where any attempt to update or create a new item results in only creating one item and then updating that same item regardless of the input. Is there something incorrect with this route? // @route POST api/item // @desc ...

Modify the h:outputText value dynamically with the power of jQuery!

Is it possible to use jQuery to dynamically change the value of my OutputText component? This is the code snippet for my component: <h:outputText id="txt_pay_days" value="0" binding="#{Attendance_Calculation.txt_pay_days}"/> I would apprecia ...

Using NodeJS to integrate WebRTC into JavaScript applications

I am facing a challenge with my JavaScript files that I need to use for creating a WebRTC application. Unfortunately, my hosting platform does not support Node.js. I'm wondering if it's possible to modify these JS files to work without Node.js. C ...

Transform a hash into an array in Perl without the need for an additional variable

Is it possible to convert a hash to an array in Perl without using an additional variable? The following code works as expected, but it utilizes another variable (@arr): perl -wlae '%hash=(name=>"linus", forename=>"torvalds "); @arr=%hash; prin ...

Is there a way to hide a paragraph or div using javascript?

I am experimenting with using buttons to hide paragraphs using javascript, but even when I set them as "hidden", there is still excess blank space left behind. Is there a way I can eliminate that extra space? Below is the javascript code: function backgro ...

Tips on revitalizing a bootstrap wizard

In my JSP file, I am using a Bootstrap wizard. You can see the wizard layout in the following link: The wizard allows me to add employee elements that are stored in a JavaScript array (I also use AngularJS). At the final step of the wizard, there is a su ...