Locating the Smallest Value in an Array of Objects

Looking at an object with keys containing arrays of objects that each have a price value. The goal is to find and return the lowest price value. In this scenario, aiming to return the value 8. Wondering if using the reduce method would be the best approach?

Sample Object

const obj =
{
   small: [{ price: 10 }, { price: 90 }],
   medium: [{ price: 33 }, { price: 8 }],
   large: [{ price: 34 }, { price: 44 }]
}

Current Code

Object.entries(obj)

Answer №1

Kindly utilize the following code snippet.

const obj =
{
   small: [{ price: 10 }, { price: 90 }],
   medium: [{ price: 33 }, { price: 8 }],
   large: [{ price: 34 }, { price: 44 }]
}

const list = Object.values(obj).flat().map(val => val.price);
console.log(Math.min(...list));

Answer №2

This code snippet utilizes the reduce() method to iterate through all the prices and identify the minimum price among them. If a price lower than the current lowest price is found, it updates the acc value which stores the lowest price. Initially, the lowest price is set to Number.MAX_SAFE_INTEGER.

const obj =
{
   small: [{ price: 10 }, { price: 90 }],
   medium: [{ price: 33 }, { price: 8 }],
   large: [{ price: 34 }, { price: 44 }]
}

const min = Object.values(obj).flat().reduce((acc, item) => 
  item.price < acc ? item.price : acc, 
Number.MAX_SAFE_INTEGER);

console.log(min);

Answer №4

Give this code a shot!

const items = {
   small: [{ cost: 10 }, { cost: 90 }],
   medium: [{ cost: 33 }, { cost: 8 }],
   large: [{ cost: 34 }, { cost: 44 }]
}

const values = Object.values(items) // [[{ cost: 10 }, { cost: 90 }], [{ cost: 33 }, { cost: 8 }], [{ cost: 34 }, { cost: 44 }]]
const flattened = values.flat() // [{ cost: 10 }, { cost: 90 }, { cost: 33 }, { cost: 8 }, { cost: 34 }, { cost: 44 }]
const costs = flattened.map(i=>i.cost) // [10, 90, 33, 8, 34, 44]
const lowest = Math.min(...costs) // 8

Another option is to use the following chain:

Math.min(...Object.values(items).flat().map(item=>item.cost))

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 can one address the issue of undefined data within table cells?

I have encountered an issue while reading and displaying an XML file on a webpage using a JavaScript script. The problem arises when the page loads, and the information inside the cells of the table shows as "UNDEFINED". The intended display should include ...

The second pop-up modal fails to appear

I have successfully implemented 2 modal windows with the help of bootstrap. The first modal is used for adding a user to the database, and the second one is meant for editing an existing user. While the first modal works perfectly fine, the editing modal d ...

Troubleshooting: Issues with AngularJS $route.reload() functionality

I have an angular app and I'm attempting to refresh the page. I've tried using $route.reload() as recommended in multiple posts, but I can't seem to get it to work (Chrome is showing me an error). Here's my controller: var app = angula ...

Utilizing jQuery to send an Ajax GET request for a JSON file

Recently I have begun delving into the world of jQuery and Ajax, attempting to utilize both technologies to retrieve a JSON FILE. Below is the structure of the file: [ { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": f ...

Mystery of the Unresponsive MD Ripple Button

While working on creating a CSS button, I wanted to incorporate the Material Design ripple or wave effect into it. I came across a simple script on codepen that works well by adding the class "ripple" to various elements such as divs, buttons, images, and ...

Issue with setting multiple checkboxes in AG Grid

I have a situation where I am trying to select multiple checkboxes on different rows in my application. Each time I click on one checkbox, it gets selected just fine. However, when I click on another checkbox in a different row, the previously selected che ...

The "tsc" command in Typescript seems to be acting up. I've exhausted all possible solutions but

Hello there, I find myself struggling to run Typescript throughout the day while utilizing Visual Studio Code. My usual method involves installing TS globally: $ npm install -g typescript But every time I try to use it, I encounter the same error: bas ...

What is preventing my function from retrieving data from the JSON File?

Exploring the realm of JSON file manipulation, I am delving into how it functions. Equipped with a JSON file attached to my document and a function sharing the same name as my object in the JSON file. However, despite all efforts, the data is not being dis ...

Unable to load nested iframe

When working with an HTML document, I tried to add an iframe in the body without any cross-origin restrictions (same URL). However, when I tried to do the same thing within the appended iframe, although the nested iframe element was successfully added to ...

AngularJS: intercepting custom 404 errors - handling responses containing URLs

Within my application, I have implemented an interceptor to handle any HTTP response errors. Here is a snippet of how it looks: var response = function(response) { if(response.config.url.indexOf('?page=') > -1) { skipException = true; ...

Utilizing jQuery to toggle nested divs within identical parent divs when they contain more than three elements using the :nth-child selector

Within my HTML markup, I have created two parent div elements that are exactly the same but contain different content. My goal is to have a functionality where if a parent div has more than 3 child div elements, a "show more" text will be displayed at the ...

Trigger the function upon displaying the modal

Within my Bootstrap project, I have set up a click event to trigger a modal as follows: $('#make_selects_modal').appendTo("body").modal('show'); My requirement is to run a function called pickClient when this modal is displayed. I att ...

What is the correct method for launching a modal window in wagtail-admin?

I am currently working on enhancing my wagtail-admin interface, but I have hit a roadblock when trying to open a modal window. While I could create a div with a close button, I believe there must be a more appropriate method for achieving this. It seems th ...

Is there a way to flip a figure that is flipped upside down?

I'm currently working on creating a map using a json file to go from d3.js to Three.js. However, when the map is displayed, it appears upside down. I'm wondering if there is a way to flip it so that it displays correctly. As a newcomer to d3 and ...

Modify the button's text with jQuery after it has been clicked

I've been struggling to update the text of a button after it's clicked, and I'm encountering an issue where it works in one part of my code but not in another. Could someone please guide me on what might be missing in my code? The first bl ...

Can you provide guidance on the most effective approach to appending to a file using async await?

Is it safe to repeatedly call functions like fs.appendFile()? For instance, when using child_process.spawn and a "for-async-of" loop to implement tee with JavaScript. Chunked file data needs to be appended to a file while performing other processing. If ap ...

Struggling to securely post data to an Express server by hashing passwords with bcrypt?

I'm currently working on developing an API using Express and Sequelize. Specifically, I am writing a function to create a new user where I utilize bcrypt for password hashing. const createNewUser = (data) => { return new Promise(async (resolve, ...

Error: Unable to access the 'clearAsyncValidators' property as it is undefined when running Jest tests on an Angular component

Encountering an Error While Testing Components with Jest Here is my code block for onClickLogin() method: onClickLogin() { if(this.loginForm.valid) { this.api.getLoginData().subscribe(res => { const user = res.find(a => { ...

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

Error encountered: "Instance variable for Apex chart not defined while attempting to update charts with updateOptions."

I have integrated Apexcharts to create charts within my application. The initial data loads perfectly upon onload, but when applying a filter, I face an issue where the charts need to be refreshed or updated with the new filtered data. I attempted to use t ...