Discovering the lengthiest strings in a multi-dimensional array using JavaScript

let lists = ["Grocery", "Clothing", "Furniture"]; 
let items = [
  [
    "tomatoes",
    "cheese",
    "bread",
    "ham"
  ],
  [
    "shirt",
    "jacket",
    "jeans"
  ],
  [
    "sofa",
    "carpet",
    "bed"
  ]
]; 

These two arrays are connected in a way that 'items' arrays are associated with each item in the 'lists' array. For instance, items[0] corresponds to lists[0], and so on.

I attempted to extract the longest string from the arrays, but my approach failed...

let longestString = (list) => {
  lists[items.reduce((a, b) => a.length > b.length ? a : b)];
  }
 console.log(`The longest item in Clothing category is: ${longestString("Clothing")}`)

Answer №1

Here’s a handy technique for finding the longest string in an array:

function findLongest(array) {
  var currentMax = "";
  for (let string of array) {
      if (string.length > currentMax.length) {
          currentMax = string;
      }
  }
  return currentMax;
}

Afterward, you can apply this function to each array in the "items" collection. I’ll let you handle that one ^^

Answer №2

One way to handle the array is to transform it into an array of strings as the outcome.

var categories = ["Grocery", "Clothing", "Furniture"],
    items = [["tomatoes", "cheese", "bread", "potatoes"], ["shirt", "jacket", "jeans"], ["sofa", "carpet", "bed"]],
    result = items.map(array => array.reduce((accumulator, value) => {
        if (!accumulator || accumulator[0].length < value.length) {
            return [value];
        }
        if (accumulator[0].length === value.length) {
            accumulator.push(value);
        }
        return accumulator;
    }, undefined));

categories.forEach((category, index) => console.log(`${category}'s longest item${result[index].length === 1 ? ' is' : 's are'} ${result[index].join(', ')}.`));
console.log(result);

Answer №3

let categories = ["Food", "Apparel", "Home Decor"]; 
let items = [
  [
    "apples",
    "ice cream",
    "baguette",
    "sweet potatoes"
  ],
  [
    "blouse",
    "coat",
    "denim"
  ],
  [
    "couch",
    "rug",
    "mattress"
  ]
]; 

var categoriesObj = categories.reduce( (obj, k, idx) => {
  obj[k] = items[idx].reduce( (res, i) => (res.length > i.length ? res : i), '' );
  return obj;
}, {} );

categories.forEach(k => console.log(`${k}'s longest item is: ${categoriesObj[k]}.`));

I trust this information proves useful to you!

Answer №4

To start, you should identify the index in the array lists that corresponds to the specified list, and then use the reduce function on that specific sub-array:

const lists = ["Grocery", "Clothing", "Furniture"]; 
const items = [["tomatoes", "cheese", "bread", "potatoes"], ["shirt", "jacket", "jeans"], ["sofa", "carpet", "bed"]]; 

const longestString = (list) => 
    items[lists.indexOf(list)].reduce((a, b) => a.length > b.length ? a : b);
console.log(`Clothing's longest item is: ${longestString("Clothing")}`)

However, it would be more efficient to store the list name and its items together in a better data structure:

const lists = {
    Grocery: ["tomatoes", "cheese", "bread", "potatoes"],
    Clothing: ["shirt", "jacket", "jeans"],
    Furniture: ["sofa", "carpet", "bed"]
}; 

const longestString = (list) => 
    lists[list].reduce((a, b) => a.length > b.length ? a : b);
console.log(`Clothing's longest item is: ${longestString("Clothing")}`)

Answer №5

Check out the code snippet below:

let categories = ["Grocery", "Clothing", "Furniture"]; 
let items = [
  [
    "tomatoes",
    "cheese",
    "bread",
    "ham"
  ],
  [
    "shirt",
    "jacket",
    "jeans"
  ],
  [
    "sofa",
    "carpet",
    "bed"
  ]
];

categories.forEach( (category, index) => {   
  let longestItem = items[index].reduce(function (a, b) { 
         return a.length > b.length ? a : b; 
      });
 
 console.log(`${category}'s longest item is: ${longestItem}`); 
 });

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

creating movement in a display of data points

(I'm just starting to learn about html5, so please keep it simple) I want to make a scatterplot of some data where the points move around over time. Right now, I am using context.arc() to create the initial frame of the animation with specific coord ...

How can I implement a single Ajax call to load content from various pages and display it

This code facilitates an ajax call to dynamically change the content of a div in the main page without requiring a full page reload: function ajaxcall() { $.ajax({ type: "POST", url: "/create.php", success: function( returnedDa ...

How to exit an ASP.NET application by pressing the exit button

I am new to asp.net and currently using Visual Studio 2012. Currently, I am working on a login page where I have two buttons: Login and Exit. Whenever I click on the Exit button, I want the application to close and also stop the debugging process. I cam ...

help a figure leap within the confines of the artwork

Take a look at my jsfiddle here: http://jsfiddle.net/2tLCk/4/ When you press the up button, Mario jumps high into the air and then comes back down. However, if you press it again, he doesn't jump. How can I fix this issue so that when the up button i ...

Help Needed: Adding a Simple Element to jQuery Tabs Script

I recently came across a fantastic jQuery tabs script on a website called Tutorialzine. The link to the article can be found here. As I was implementing this script, I realized I needed to customize it by adding specific classes to certain tabs. Specifica ...

Tips for accessing a variable through request.query

When I made a call to getContents() in my client-side code: $.getJSon("/getContents", function(room){ theRoom=$("#roomName").val();//textarea's value ... }); I am now trying to figure out how to retrieve theRoom variable in getContents(), which is ...

Modifying the appearance of a CSS element with jQuery: Step-by-step guide

The code I have is as follows: $('.signup-form-wrapper').css("style", "display: block"); $('.login-form-wrapper').css("style", "display: none"); I'm not sure why it's not working. The current appearance of ...

Having trouble displaying a background image on a React application

Public>images>img-2.jpg src>components>pages>Services.js> import React from 'react'; import '../../App.css'; export default function Services() { return <h1 className='services ...

Utilize VueJS to bind a flat array to a v-model through the selection of multiple checkboxes

My Vue component includes checkboxes that have an array of items as their value: <div v-for="group in groups"> <input type="checkbox" v-model="selected" :value="group"> <template v-for="item in group"> <input type ...

Tips for resolving a flickering issue that occurs when switching to an input field with our default value / placeholder plugin

In the realm of web development, numerous plugins cater to the implementation of HTML5's placeholder attribute in older browsers. The plugin we have opted for can be found here. Unlike some other alternatives, this particular plugin, with a few modif ...

Error: Validation error occurred with document - reason unknown

Recently, I've been working on developing a basic CRUD application using MongoDB as my database. However, I keep encountering an error labeled MongoError: Document failed validation, and I am struggling to pinpoint the issue. The data appears to be s ...

Identifying geometric coordinates within Canvas

Currently, I am adding drag and drop functionality to my HTML5 Canvas application. I have encountered a challenge in determining how to detect if the shape being clicked on is not a rectangle or square. For instance, within my 'mousedown' event h ...

Exploring the Strategy of Incorporating Dynamic Keys into TypeScript for Easy Referencing

I am facing a scenario where I receive keys from the backend and need to design an interface based on these keys. By creating a dynamic interface, I can easily bind these properties. const KEYS_FROM_API = ['ARE_YOU_SURE', 'NOT_NOW', &ap ...

I received no response when I checked my Discord messages

I'm currently working on creating a bot that will send a daily morning message at 9 o'clock with a customizable reaction. Right now, it's successfully sending the message on Discord but there seems to be an issue with the reaction part. Can ...

What could be causing the malfunction in one of the functions within my JavaScript code?

As a JavaScript beginner, I am currently working on creating a To-do App with JavaScript. Most of the functions are functioning perfectly except for one called doneTask at line 36. Despite numerous attempts to identify the issue, I have been unsuccessful s ...

How can I resolve the issue of neglecting the result of `inputstream.read` in IntelliJ?

Currently, I am in the process of resolving potential bugs within my application. To evaluate my code, I have decided to utilize Sonar. However, I have encountered an issue that has left me puzzled: private Cipher readKey(InputStream re) throws Exception ...

The value assigned to a dynamically created array in a void function may not be the same when returned in the main() function

Having a bit of trouble with dynamic arrays in my C program. Everything was running smoothly until I was required to move the creation of the dynamic array into a separate void function. After doing so, the program continued to work fine until I needed to ...

Modifying the data attribute within the div does not result in a different image for the 360-degree spin view

My current project involves utilizing js-cloudimage-360-view.min.js to create a 360-degree view of images. I have successfully retrieved the images, but I am encountering difficulty in updating the images by clicking a button. index.html <!DOCTYPE html ...

Error: Uncaught ReferenceError: d3 is undefined. The script is not properly referenced

Entering the world of web development, I usually find solutions on Stack Overflow. However, this time I'm facing a challenge. I am using Firefox 32 with Firebug as my debugger. The webpage I have locally runs with the following HTML Code <!DOCTYP ...

When toggling between light and dark themes using the useMediaQuery hook, the Material-ui styling is being overridden

While working with next.js and material-ui, I encountered an issue where the theme would change based on user preference. However, when switching to light mode, the JSS Styles that I had set were being overwritten. This problem only seemed to occur in ligh ...