Determine which array within an object is the longest in terms of length

Currently, I'm incorporating lodash.js into my project but it seems that there is no built-in method to achieve what I need. Even after attempting it on my own, I find myself dissatisfied with the outcome.

function findLargestArrayInObject(object) {
  var counter = 0;
  for (let property in object) {
    if (object.hasOwnProperty(property)) {
      counter = object[property].length > counter ? object[property].length : counter
    }
  }
  return counter
}

var obj = {
  a: [2, 3, 4, 5],
  b: [2, 3, 4],
  c: [2, 3],
  d: [2],
}

console.log(findLargestArrayInObject(obj)) // => should return the length of array (a)

There's something missing here that I can't quite grasp.

Answer №1

To retrieve the values from the object, utilize Object.values, convert them to their respective lengths, and then apply reduce to locate the highest value:

Object.values(obj).map(item => item.length).reduce((a, b) => Math.max(a, b))

Answer №2

In the case of Lodash being used, the _.max function can be utilized:

_.max(Object.values(obj).map(a => a.length))

Answer №3

element, there is a more concise method to accomplish this task by utilizing the Math.max function:
function findMaxArrayLengthInObject(obj) {
  return Math.max(...Object.values(obj).map(element => element.length));
}

Answer №4

const data = {
  x: [4,5,6],
  y: [7,8,9],
  z: [10,11],
}

_.chain(data)
.reduce((high, value, key) => {
  if (value.length > high.maxLen){
    high.maxLen = value.length;
    high.propKey = key;
  };
  return high
}, {maxLen: -1, propKey: ''})
.get('propKey').value()

Perform a reduction on the data object and extract the property key from the result

Answer №5

To utilize lodash, the reduce function can be employed

_.reduce(data, (initialValue, element) => element.size > initialValue ? element.size : initialValue, 0);

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

What is the best way to implement jQuery on an HTML file instead of relying solely on the Document Object Model

My attempt to make modifications to an HTML document has been challenging, as it differs from working with the DOM. I've realized that the syntax I typically use with the DOM doesn't translate well to this other document. For instance, while I co ...

What are the steps to implement an Express Error handling middleware in my specific scenario?

I have implemented a router middleware to validate requests and a global Error handler middleware in the server.js file to handle all errors. However, I am encountering an issue within the router while trying to implement this logic. The problem is highli ...

Accessing parent variables from child components in Angular can be accomplished by utilizing input

I am working with four components and I have a need to pass data from a parent component to a child component. The structure defined within the map.html template is as follows: <map-builder [width]="width"> <layer [name]="'markerLayer&ap ...

Adding a static global constant in webpack dynamically

I'm facing a challenge with adding a global constant to my project using webpack.DefinePlugin. I've successfully added one in the module.exports, but I struggle to do this conditionally. When I declare and use '__VERSION__' in my module ...

Converting to lower case with Jexl and making replacements in the text

Currently, my code uses the jexl.eval function to evaluate a value like so: jexl.eval("dataset[0].data['Entity Name'].toLowerCase().replace(/ /g, '_')", data); The value of dataset[0].data['Entity Name'] is always a ...

Determining where to implement the API display logic - on the server side or

Currently, I am in the process of restructuring an API that deals with user profiles stored in one table and profile images in another. The current setup involves querying the profiles table first and then looping through the images table to gather the ass ...

Incorporate extra padding for raised text on canvas

I have a project in progress where I am working on implementing live text engraving on a bracelet using a canvas overlay. Here is the link to my code snippet: var first = true; startIt(); function startIt() { const canvasDiv = document.getElement ...

What could be the reason for my onChange event not functioning properly?

The issue I'm experiencing involves my onchange event not properly copying the text from the current span to the hidden field. Any ideas on why this might be happening? Check out my code at this link. ...

Error: WebView element type is not valid. A valid string was expected

Here is my basic React code : import React from "react"; import { Text, StyleSheet,View } from "react-native"; import { WebView } from 'react-native'; const App = () => { return( <WebView source={{ ...

Looking to dynamically display users added to an array in a table using Angular and JavaScript?

As a newcomer to javascript and angularjs, I recently attempted to build a table that would display all users in an array dynamically as new users are added through a form. However, each time I run my code, I encounter the error message "Fill out the entir ...

Structuring files with AJAX, PHP, Javascript, and HTML

Explaining my dilemma in detail might be a bit abstract, but I'll try to do my best. In one of my PHP files, I have HTML code that includes text boxes and a submit button. This file serves as the main page and is named mainHTML.php The text boxes ar ...

At what point does the component type of an array type also become another array type?

The beginning of section 10 in the JLS introduces an interesting concept: An array's component type can itself be another array type, leading to components that reference subarrays. It is a fascinating structure where one delves into the component t ...

Troubleshooting Issue with Query Functionality in MEAN App's Find Request

I'm facing some challenges while working with queries in my MEAN App. Specifically, I am attempting to retrieve data that matches the input entered into a search field: $scope.searchInput = function(search){ $http({ method: 'GET', url: ...

Is there a way to break down a text document into separate arrays based on blank spaces?

I have a shell command that generates text structured like this: Header A - Point 1 - Point 2 Header B - Point 1 - Point 2 Header C -Point 1 - Point 2 ... My goal is to parse this text into an array, with each element separated by the empty line. For ...

Need Root Directories in Browserify and Using NPM (eliminating the constant use of '../../../..' in both cases)

Despite my extensive search for a solution to this issue, I have been unsuccessful so far – even after referring to the amazing gist on improving local require paths and thoroughly reading the Browserify handbook section on Avoiding ../../../../... I am ...

The parameter of type '{ [key:string]:any;}' cannot be assigned a string argument

When attempting to attach a click event handler on a TypeScript file, I encountered the following error message: Argument of type 'string' is not assignable to parameter of type '{ [key:string]:any;} https://i.sstatic.net/ATkz0.png The ...

Is there a way for me to initialize a PHP array using data from an AJAX call?

Trying to fetch data from an ajax request and potentially set a php array seems challenging as one operates on the client side while the other on the server side. Below is the code: HTML page: <?php foreach ($products as $product): ?> <li> ...

Synchronize two slideshows in a cycle with timed delays between each cycle

Is there a way to add a sequential delay between slideshows in the synchronized slide show example from cycle2 API? For example, having each div.cycle-slideshow start at 5s intervals (5s, 10s, 15s, 20s...). The cycle would then repeat with the first div st ...

Ways to fix a "define is not defined" issue when utilizing jasmine karma with compiled typescript for component testing

I'm faced with an issue in my typescript app where the compiled code is stored in a single file named myjs.js within the js folder. Additionally, I have karma jasmine configured on my workspace. Inside myjs.js, there's a segment of code like thi ...

Ways to achieve outcomes from functions employing concatMap within rxjs?

When calling two functions, I make use of fn1 and fn2. To execute them one after the other, I utilize concatMap. I choose not to use exhaustMap and switchMap as they can result in nested "callback-hell". exhaustMap(() => fn1().pipe( swit ...