Tips for determining the minimum value within an array of objects across multiple keys using a single function

I am currently tasked with the challenge of determining the minimum value from an array of objects that contain multiple keys. My ultimate goal is to identify the minimum value among all keys or specific keys within the objects.

For instance

var users = [
    {id:"1", name:"ABC", age:30, height: 75, weight: 83},
    {id:"1", name:"ABC", age:24, height: 63, weight: 75},
    {id:"1", name:"ABC", age:27, height: 56, weight: 55}
]

In the given example, my aim is to locate the user(s) with the lowest age, height, and weight values, all using a single function.

The current function I have been utilizing only identifies the minimum age.

findMin(data) {
        return data.reduce((min, u) => u.age < min ? u.age : min, data[0].age);
    },

Answer №1

Feel free to give this a shot:

const items = [ {id:"1", name:"ABC", age:30, height: 75, weight: 83}, {id:"1", name:"ABC", age:24, height: 63, weight: 75}, {id:"1", name:"ABC", age:27, height: 56, weight: 55} ];
const minimum = (arr, key) => arr.reduce((min, el) => el[key] < min[key] ? el : min);
const attributes = ['age', 'height', 'weight'];
const output = Object.fromEntries(attributes.map(attr => [attr, minimum(items, attr)]));
console.log(output)

Utilizing just one function:

const items = [ {id:"1", name:"ABC", age:30, height: 75, weight: 83}, {id:"1", name:"ABC", age:24, height: 63, weight: 75}, {id:"1", name:"ABC", age:27, height: 56, weight: 55} ];

const minimum = (arr, attrs) => arr.reduce(
  (min, el) => Object.fromEntries(attrs.map(attr => [attr, el[attr] < min[attr][attr] ? el : min[attr]])), 
  {age: arr[0], height: arr[0], weight: arr[0]}
 );

const result = minimum(items, ['age', 'height', 'weight']);
console.log(result)

Result :

{
    age: { minAgeItem },
    weight: { minWeightItem },
    height: { minHeightItem }
}

Answer №2

This is a customized update!

const data = [{
    id: "1",
    name: "XYZ",
    age: 32,
    height: 70,
    weight: 85
  },
  {
    id: "2",
    name: "DEF",
    age: 25,
    height: 65,
    weight: 78
  },
  {
    id: "3",
    name: "GHI",
    age: 28,
    height: 58,
    weight: 60
  }
];

function findMinimumValues(arr) {
  let minAge = Infinity,
    minHeight = Infinity,
    minWeight = Infinity;
  const results = [{}, {}, {}];
  arr.forEach((item) => {
    if (item.age <= minAge) {
      minAge = item.age;
      results[0] = item;
    }
    if (item.height <= minHeight) {
      minHeight = item.height;
      results[1] = item;
    }
    if (item.weight <= minWeight) {
      minWeight = item.weight;
      results[2] = item;
    }

  });
  return results;
}

console.log(findMinimumValues(data));

Answer №3

I believe I have a good understanding of your request to extract the minimum value for each field. To achieve this, you can enhance your functions to return an object as shown below:

For accurate results, I recommend opening the Chrome console for output verification as the Stack Overflow console may provide unexpected outcomes.

var users = [
    {id:"1", name:"ABC", age:30, height: 75, weight: 83},
    {id:"1", name:"ABC", age:24, height: 63, weight: 75},
    {id:"1", name:"ABC", age:27, height: 56, weight: 55}
]

function findMin(data) {
  return data.reduce((mins, u) => {
    mins['minAge'] = (u.age < mins['minAge'] ? u.age : mins['minAge']);
    mins['minHeight'] = (u.height < mins['minHeight'] ? u.height : mins['minHeight']);
    mins['minWeight'] = (u.weight < mins['minWeight'] ? u.weight : mins['minWeight']);
    return mins
  }, {
    minAge: data[0].age,
    minHeight: data[0].height,
    minWeight: data[0].weight
  });
}

console.log(findMin(users))

edit: Enhanced flexibility in the function:

var users = [
{ id: "1", name: "ABC", age: 30, height: 75, weight: 83 },
  { id: "1", name: "ABC", age: 24, height: 63, weight: 75 },
  { id: "1", name: "ABC", age: 27, height: 56, weight: 55 }
];

function findMin(data, keys) {
  return data.reduce((mins, u) => {
    keys.forEach(
      (key) => (mins[key] = u[key] < mins[key] ? u[key] : mins[key])
    );
    return mins;
  }, keys.reduce((accumulator, value) => {
    return {...accumulator, [value]: data[0][value]};
  }, {}));
}

console.log(findMin(users, ['age','height']));

Answer №4

Here is an alternative method:

const people = [
    {id:"1", name:"ABC", age:30, height: 75, weight: 83},
    {id:"2", name:"ABC", age:24, height: 63, weight: 75},
    {id:"3", name:"ABC", age:27, height: 56, weight: 55},
];

const getMinsByAttribute = (people, attributes) => {
  const minByAttribute = (attribute) => people.reduce((min, current) => (min[attribute] > current[attribute]) ? current : min)
  
  return attributes.reduce((accumulator, attribute) => ({ ...accumulator, [attribute]: minByAttribute(attribute) }), {});
};

console.log(getMinsByAttribute(people, ['age', 'height', 'weight']));
.as-console-wrapper { max-height: 100% !important; top: 0 }

Answer №5

To organize the array by age, height, and weight, you can use the following code:

objs.sort((a,b)=> (a.age - b.age || a.height - b.height || a.weight - 
 b.weight));

This method allows you to include additional sorting criteria in any order you require.

The code above is analogous to the SQL query below:

SELECT * FROM OBJS ORDER BY NAME,AGE,ROLLNO;

It is recommended to perform this sorting on the backend rather than the frontend to simplify things for the frontend.

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

Mistakes following update to Angular 4 from Angular 2

After upgrading from Angular2 to Angular4, I encountered these errors in the CLI. While my app continues to function after the upgrade, I am curious about possible solutions to resolve these errors. Any suggestions? https://i.stack.imgur.com/CyYqw.png He ...

Encountered an issue while trying to install the package '@angular/cli'

Encountered errors while attempting to install @angular/cli using npm install -g @angular/cli. The node and npm versions on my system are as follows: C:\WINDOWS\system32>node -v v 12.4.0 C:\WINDOWS\system32>npm -v 'C ...

Tips on incorporating express-mysql-session in a TypeScript project

I'm experimenting with using express-session and express-mysql-session in a Typescript project. Here's the relevant snippet of my code: import * as express from "express"; import * as expressSession from "express-session"; import * as expressMyS ...

What is the best way to transform a one-dimensional object array into a two-dimensional array in a Vue component, based on a specific key?

My vue modules are structured like this: [types.GET_PRODUCT_CATEGORIES] (state,{ stores }) { state.product_categories = {} console.log(stores); stores.forEach(message => { set(state.product_categories, message.id ...

Configure WebStorm so that node_modules is set as the library root, while simultaneously excluding it from indexing

Can WebStorm projects be configured to set the node_modules as the library root, while also excluding it from indexing? I thought I saw a project that had node_modules marked as both library root and excluded, but I'm unsure how to do this. Does anyo ...

The Angular2 module x.module does not contain the exported member NavComponent

Encountering difficulties with rc.5 of Angular2. I have created an NgModule named xModule where I define NavComponent and export it. This is specified in the file x.module.ts. However, when attempting to import xModule into yModule and export NavComponent ...

Managing automatic page redirects in Ajax requests

For the past two days, I have been encountering a challenging issue with my Laravel application that is hosted on Heroku server. The app allows file uploads through an ajax request, displaying upload progress on the page and returning JSON response upon co ...

Is there a way to determine if a tuple is of infinite or finite length?

Is there a way to determine if a tuple is finite or infinite? I've been working on a solution, but it doesn't cover all cases: type IsFinite<T extends any[], Finite = true, Infinite = false> = T extends [] ? Finite : T extends (infer E ...

Is there a built-in method in Next.js 13 to secure routes from unauthorized access?

In my project, I have the following pages: /about, /user, and /user/[id]. Unfortunately, I am unable to access req.page, which provides the slug (i.e. /user/[id]), making it difficult for me to implement logic to redirect requests from unauthenticated user ...

Only function components can utilize hooks within their body. The useState functionality is currently not functioning as expected

Currently working on a GatsbyJS project and attempting to utilize a Hook, however encountering an error message. Initially, I decided to remove the node_modules folder and package.json.lock file, then executed npm install again, unfortunately without reso ...

What causes the difference in behavior between using setInterval() with a named function as an argument versus using an anonymous function?

I can't seem to figure out why using the function name in setInterval is causing issues, while passing an anonymous function works perfectly fine. In the example that's not working (it's logging NaN to the console and before the first call, ...

The code for the bouncing image isn't functioning properly outside of the JSFiddle environment

I'm having issues with this jQuery snippet in my web application. It works fine on jsfiddle, but not when I add it to my project. Here's the code: $('.myimage').mouseenter(function() { $(this).effect('bounce',500); }); Her ...

How can you switch the display between two different class names using JavaScript?

I currently have a total of four filter buttons on my website, and I only want two of them to be visible at any given time. To achieve this, I labeled the first set of buttons as .switch1 and the second set as .switch2. Now, I've added a 'switch ...

Data from the server isn't loading in Angular2

I have successfully developed a basic Java app using REST that returns a string value when accessed through a REST client. However, I am now facing an issue in fetching the string value using an Http REST client in Angular2. I have set up a service to retr ...

The v-model in the Vue data() object input is not functioning properly and requires a page refresh to work correctly

Explaining this situation is quite challenging, so I created a video to demonstrate what's happening: https://www.youtube.com/watch?v=md0FWeRhVkE To break it down: A new account can be created by a user. Upon creation, the user is automatically log ...

Unable to display modal pop-up in ASP.NET Core MVC web application

I have developed a web application using ASP.NET CORE MVC. I encountered an unusual issue while trying to display a modal popup using JQuery. The div structure I am working with is as follows: <div class="modal fade" tabindex="-1" r ...

Dominant Editing through ASP.Net Roles

Looking for guidance on how to effectively use knockout with asp.net membership roles in MVC 4. My goal is to incorporate an editable grid on the page based on whether the user is an administrator or a 'registered user'. I want to ensure that use ...

Swagger Issue Resolved: Restriction on Number of Params Set

After setting up this option for my route, I noticed that when accessing the first parameter (page), it correctly returns the value entered in Swagger UI. However, when trying to access the second parameter (genre), it seems to interpret it as a string &ap ...

Enhancing the session helper in Silex with additional values

Hey there, I'm currently working on a basic shopping cart using an MVC framework called Silex. However, I've run into a JavaScript/AJAX issue that I could use some help with. My problem arises when trying to add a product to the basket. The issue ...

Having a slight hiccup with pixel alignment and browser compatibility in my jQuery animation

To emphasize a specific paragraph element, I developed a JavaScript function that displays it above a darkened background. My approach involved using jQuery to generate an overlay and then duplicating the targeted paragraph element while positioning it ab ...