Streamlining a map-generated object

Looking to streamline this code, specifically the declaration of the variable codes. Is there a way to simplify this?

const numbers = [
  { id1: 1, id2: 2, id3: 3, pos: "a" },
  { id1: 4, id2: 5, id3: 6, pos: "b" },
  { id1: 7, id2: 8, id3: 9, pos: "c" }
];

let codes = {
  id1: Math.max.apply(
    Math,
    numbers.map((n) => {
      return n.id1;
    })
  ),
  id2: Math.max.apply(
    Math,
    numbers.map((n) => {
      return n.id2;
    })
  ),
  id3: Math.max.apply(
    Math,
    numbers.map((n) => {
      return n.id3;
    })
  )
};

console.log(codes);

I'm aiming to condense this code while retaining the same data structure. Any suggestions on how to implement a loop or simplify further?

Appreciate any assistance!

Answer №1

To extract the id keys, utilize the Object.fromEntries function to link each key to an array of values associated with that key. Then, apply Math.max on the set of numbers corresponding to each key within the numbers array:

const numbers = [
  { id1: 1, id2: 2, id3: 3, pos: "a" },
  { id1: 4, id2: 5, id3: 6, pos: "b" },
  { id1: 7, id2: 8, id3: 9, pos: "c" }
];
const codes = Object.fromEntries(
  Object.keys(numbers[0]).slice(0, 3).map(
    key => ([
      key,
      Math.max(...numbers.map(obj => obj[key]))
    ])
  )
);
console.log(codes);

Answer №2

To take a more dynamic approach, consider creating an array that contains the keys you want to focus on.

const data = [{ name: 'Alice', age: 30, city: 'New York' }, { name: 'Bob', age: 25, city: 'Los Angeles' }, { name: 'Charlie', age: 35, city: 'Chicago' }],
    keys = ['name', 'age', 'city'],
    results = data.reduce((acc, obj) => {
        keys.forEach(key => acc[key] = Math.max(key in acc ? acc[key] : -Infinity, obj[key]));
        return acc;
    }, {});

console.log(results);

Answer №3

Efficiently iterate through object keys

const elements = [
  { element1: 1, element2: 2, element3: 3, position: "a" },
  { element1: 4, element2: 5, element3: 6, position: "b" },
  { element1: 7, element2: 8, element3: 9, position: "c" }
];

const maxValues = {};
elements.forEach(item =>
  Object.entries(item).forEach(([key, value]) => {
    if (maxValues[key] === undefined || value > maxValues[key]) maxValues[key] = value;
  })
);

console.log(maxValues);

If you wish to iterate over specific properties, consider using an array of keys for iteration.

const elements = [
  { element1: 1, element2: 2, element3: 3, position: "a" },
  { element1: 4, element2: 5, element3: 6, position: "b" },
  { element1: 7, element2: 8, element3: 9, position: "c" }
];

var keysToIterate = ['element1', 'element2', 'element3'];

const maxValues = {};
elements.forEach(item =>
  keysToIterate.forEach(key => {
    if (maxValues[key] === undefined || item[key] > maxValues[key]) maxValues[key] = item[key];
  })
);

console.log(maxValues);

Answer №4

You can achieve the same result using a simple for loop

let codes = {};
for(let i=1; i<= 3; i++){
    codes['id' + i] = Math.max.apply(Math, numbers.map(n => n['id' + i]));
}

Answer №5

To start, define the property you wish to calculate.

const data = [
  { key1: 1, key2: 2, key3: 3, position: "A" },
  { key1: 4, key2: 5, key3: 6, position: "B" },
  { key1: 7, key2: 8, key3: 9, position: "C" },
]

const properties = ["key1", "key2", "key3"]

let values = Object.fromEntries(
  properties.map((property) => [
    property,
    Math.max(...data.map((item) => item[property])),
  ])
)

console.log(values)

Answer №6

Here is my take on the problem:

const data = [
    { key1: 11, key2: 22, key3: 33, loc: "x" },
    { key1: 44, key2: 55, key3: 66, loc: "y" },
    { key1: 77, key2: 88, key3: 99, loc: "z" }
];

let values = {};
['key1', 'key2', 'key3'].forEach(key => {
    values[key] = Math.max.apply(
        Math,
        data.map(d => d[key])
    )
});

console.log(values);

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

Enhance your live table previews with the power of React JS

I'm trying to optimize the process of live updating a table in React. Currently, I am using setInterval which sends unnecessary requests to the server. Is there a more efficient way to achieve this without overwhelming the server with these unnecessar ...

Navigating production mode in nuxtjs and uncovering errors

There seem to be numerous inquiries regarding this matter. Unfortunately, there doesn't appear to be a definitive solution. Is there any way to view detailed error logs in production mode? https://i.stack.imgur.com/prXUt.jpg ...

What causes the "Cannot read properties of undefined" error in Vue when an array is initialized and output is still being displayed?

I am working with two vue files, namely App.vue and a component called UsersPage.vue. UsersPage.vue: <script> export default { data:() =>({ usersList : [] }), methods:{ async createUsersList(){ this.usersLi ...

Looking for a seamless way to convert jsp code to html using sightly in AEM 6.1?

I need help transforming JSP code to HTML using Sightly in AEM. In the JSP code, we have a scriptlet that stores a value from the dialog into a JSP variable called "coltype" using the code pageContext.setAttribute("coltype", xssAPI.filterHTML(properties. ...

What is the best way to conceal a div in React using components?

Below is the code I have for my App: import React, {Component} from 'react'; import App1 from './App1'; class App extends Component { render(){ return ( <> <App1/> ...

Saving data in multiple collections using MongoDB and Node.js: A comprehensive guide

In a recent project of mine, I have implemented a combination of nodeJS and mongodb. My main goal is to store data in multiple collections using just one save button. Below is the code snippet that I am currently working with: var lastInsertId; loginDat ...

What could this error be in Chrome console: "Uncaught SyntaxError: Unexpected token ':'"

Why am I getting this error in the Chrome console: "Uncaught SyntaxError: Unexpected token ':'"? I have a JSON file located at the root of my application: <script src="levels.json"></script> Here is the content of my JSON file: { ...

Troubleshooting Cross-Origin Resource Sharing problem with Stripe API integration in Angular

I am diving into the world of Stripe API and CORS for the first time. I've set up a POST request from Angular to my Node.js server. Since the client origin differs from the server destination, I have implemented CORS on the server side. When inspectin ...

Issue encountered while generating REST API through Postman resulting in a 500 error

I am in the process of creating a Node.js API for a web application. The GET request is functioning properly, however, when attempting to execute a POST request, I encounter an error messageError Below is the code snippet: //User Schema const mongoose ...

Updating a global variable in Angular after making an HTTP call

I'm facing a challenge where I have a global variable that needs to be updated after an HTTP GET call. Once updated, I then need to pass this updated variable to another function. I'm struggling to figure out the best approach for achieving this. ...

Is it feasible to create a doughnut chart with curved edges?

My goal is to create a doughnut chart, but my search for reliable CSS/SVG/Canvas solutions has not been successful. https://i.sstatic.net/Rq6Lx.jpg I want each segment to have fully rounded corners, which presents a unique challenge. ...

submission not being processed on form

I've spent the last 3 hours searching for this elusive error, but to no avail. It seems that the onsubmit function is not triggering for some unknown reason. My goal is to ensure that the user inputs a non-negative number in each field. <!DOCTYP ...

Sending Data from jQueryUI Dialog to PHP using AJAX

I am struggling to retrieve the user inputs from text fields within a dialog window in order to utilize them for a SQL query. The issue I am encountering is that I am unable to effectively use the array in PHP. Despite no error messages being displayed, I ...

Setting up 'ngProgress' as a loader in my project using the 'ngbp boilerplate' is straightforward and easily customizable

Currently, I am utilizing the 'ngbp' angular boilerplate from GitHub to develop my project. My goal is to implement ngProgress for displaying a loader when navigating between sections. I have successfully installed ngProgress via bower and ensur ...

Having trouble updating the sequelize-cli configuration to a dynamic configuration

Encountering an issue while attempting to switch the sequelize-cli configuration to dynamic configuration, following the instructions in the documentation. I have created the .sequelizerc-file in the project's root directory and set up the path to con ...

VueJS's approach to routing through modular components

I am currently working on a website where I need to set up different category pages using dynamic routes. To achieve this, I am utilizing vue-router and aiming for a single dynamic route that can switch between pages by loading different components. Here ...

Activate $digest when a variable is modified by a node.js function

I am currently working on developing an application using node-webkit and AngularJS. Everything was going smoothly until I tried to make Angular watch over a "legacy variable" using the method outlined in this answer, which led to an Error: [$rootScope:inp ...

Guide to running examples of three.js on a local web browser

Currently, I am attempting to run the examples from three.js locally in a web browser on MacOS. To do this, I have cloned the entire three.js repository and attempted to open a file in a browser (such as three.js/examples/misc_controls_orbit.html). However ...

Discover the steps to showcase a specific option from a select list at the top row through VueJs

Below is the code to iterate through the elements of teamLeaderOfWithDescendants <option :value="item.user_id" v-for="item in teamLeaderOfWithDescendants"> {{item.user_full_name}} </option> Is there a way to prioritize the row where item.u ...

A platform for creating ER and flow diagrams specifically tailored for web applications, utilizing open source software

Our team is currently working on creating a web application that enables users to create diagrams, such as flow or ER diagrams. We are looking for ways to convert these diagrams into XML or other formats for representation. Are there any open-source soft ...