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

How to resolve the Angular SSR authentication guard issue to briefly display the login page upon refreshing?

I have a love-hate relationship with auth.guard.ts: import { Injectable } from '@angular/core'; import { CanActivateChild, Router } from '@angular/router'; import { Observable, of } from 'rxjs'; import { AuthService } from &a ...

Guide on setting up a chart using data fetched from an API?

I'm looking to incorporate ngx-charts into my project, but I'm struggling with initializing the chart with data retrieved from my API. Setting up a vertical bar chart seems straightforward. The data structure I have is like this: https://stackb ...

"Encountered an error: AngularJS is unable to read the property 'push' as it is

I'm attempting to generate an array using data retrieved from an API. However, I continue to encounter an error message stating cannot read property 'push' of undefined in Javascript. Could someone please guide me on how to resolve this iss ...

Manipulating the content of h1 tag using Jquery when selecting from a dropdown menu

As I was exploring this Fiddle I stumbled upon, http://jsfiddle.net/JBjXN/ I've been working on a functionality where selecting an option from HTML <h1>Select a Show</h1> <select class="radio-line" id="radio-manager&quo ...

Unexpected disconnection from Socket.io server

Utilizing node.js service and angular client with socket.io for extended duration http requests. Service: export const socketArray: SocketIO.Socket[] = []; export let socketMapping: {[socketId: string]: number} = {}; const socketRegister: hapi.Plugin< ...

Can you explain the term used to describe when specific sections of the source code are run during the build process to improve optimization?

One interesting feature I've noticed in next.js is its automatic code optimization during the build process. This means that instead of running the code every time the app is executed, it's evaluated and executed only once during the build. For ...

Encountering Uncaught Syntax Error when attempting a request with JSON parameters

Currently, I am using Fetch to send a post request to my server while including some additional information. Here's the code snippet: var rating = document.getElementById("rating"); var ratingValue = rating.innerHTML; fetch("/films",{ method: "po ...

"Troubleshooting: Why are errors not appearing in ts-node

Whenever I encounter an error in my code while compiling with ts-node, the error does not seem to appear in the console. For instance:let data = await fs.readFileSync(path); In the following code snippet, I am using "fs" to read a file by passing a path ...

What are the best practices for managing mouse events in AlpineJS when working with my menu?

I'm currently tackling the challenge of developing a mega dropdown menu feature using alpine.js and Tailwind CSS. Unfortunately, I've hit a roadblock as I can't seem to get the mouse events functioning correctly. In the snippet below, you&ap ...

Angular router link circles back to its originator

I've been working on a basic login page that transitions to a homepage once the user successfully logs in. So far, I've focused solely on the HTML structure of the login component without implementing any code in the corresponding TypeScript file ...

sending data from a callback to an express router

As I embark on learning node.js, I've encountered a challenging issue. In my passportAuth.js file, I create a user and have a callback to ensure the user is created successfully. The code snippet looks something like this: req.tmpPassport = {}; var ...

Generate a layout of interactive components and save them into a collection

My idea involves creating a pandemic simulation that demonstrates how a virus can impact different countries based on factors like wealth, population, and temperature. I have drawn a concept for three countries with grids that change color to indicate infe ...

React.js Form Validation issue: When using input type "number", the text field remains a single value even after attempting to delete characters with the backspace key

Experiencing difficulty in clearing the input field value, even after pressing backspace the value remains constant. One particular value persists in the input field. import * as React from "react"; import { Button, Form } from "react-boots ...

JS form validation malfunctioning

XHTML <form name="suggestion" method="post" action="suggestion.php" class="elegant-aero" onSubmit="return validate()" > <label> <span>Message :</span> <textarea id="Message" name="m ...

Why is it necessary to use 'then' on the response JSON when using the Fetch API? It's like trying to decipher the hidden meaning

While delving into the realm of promises, I decided to test it out with a basic GET request on Twitch. Yet, one aspect is still puzzling me - why does json() return a promise? The response already contains the data, so what's the deal with it being wr ...

Tips on adjusting a position that shifts with changes in window size

Working on a website for my grandpa, I'm planning to include a small biker character that runs across the screen. When hovered over, he stops and advises "wear a helmet." The animation works well, but there's an issue with the positioning when th ...

Setting up Webpack for Node applications

My current challenge involves configuring Webpack for a node app that already exists. I am encountering various issues and struggling to find solutions or even know where to begin. Situation The project's folder structure is as follows: +---app +-- ...

Dealing with 401 Errors: Navigating Redirects using Vue.js and

Currently, I am utilizing Vue.js along with axios in an attempt to create a generic API object as shown below: import router from './router' import auth from './auth' const axios = require('axios') export const API = axios.c ...

Testing the use of rxjs fromEvent in Angular while mocking subscriptions

In the Angular component, I have an array of objects representing companies that are provided via @Input(). Upon loading this data, which is obtained from an HTTP request, I assign it to another variable called filteredList, which is used in an *ngFor dire ...

What is the best way to implement persistStore in Redux-Toolkit?

Here is my setup: import AsyncStorage from '@react-native-async-storage/async-storage' import { persistStore, persistReducer } from 'redux-persist'; import { configureStore } from "@reduxjs/toolkit"; import { searchReducer } f ...