Find the tiniest array within a collection of arrays

Looking at an array filled with various arrays, I am aiming to pinpoint the shortest path available within the paths array.

paths = [ 
   ["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"],
   ["RIGHT", "LEFT", "TOP"],
   ["TOP", "LEFT"]
];

paths.map((path)=> Math.min(path.length));

Answer №1

Utilize the Array#reduce function.

var routes = [
  ["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"],
  ["RIGHT", "LEFT", "TOP"],
  ["TOP", "LEFT"]
];

console.log(routes.reduce((previous, next) => previous.length > next.length ? next : previous))

Answer №2

To find the shortest path, you can utilize the Array sort method and compare the length of each array. This approach appears to be the most direct way.

let routes = [
  ["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"],
  ["RIGHT", "LEFT", "TOP"],
  ["TOP", "LEFT"]
];
const [shortestRoute] = routes.sort((a,b) => a.length - b.length);
console.log(shortestRoute);

Answer №3

If you're looking to gather arrays that are either smaller or of equal length.

let paths = [["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"], ["RIGHT", "LEFT", "TOP"], ["TOP", "LEFT"]],
    result = paths.reduce((r, a, i) => {
        if (!i || a.length < r[0].length) {
            return [a];
        }
        if (a.length === r[0].length) {
            r.push(a);
        }
        return r;
    }, []);

console.log(result);

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

Vue component encounters undefined error when passing prop array through component

My challenge is passing an array of dates to my component, but I keep encountering this error: [Vue warn]: Property or method "dates" is not defined on the instance but referenced during render I'm puzzled by this issue because I am receiving the ...

How to Utilize ngIf and ngFor Together in Angular 4 for the Same Element in ngFor

Just starting with Angular 4 and experiencing a roadblock in my code. Here is the snippet of my code: JSON: [{"name": "A", "date": "2017-01-01", "value": "103.57"}, {"name": "A", "date": "2017-01-08", "value": "132.17"}, ...

Is an encrypted JSON API that utilizes cookies for authentication and nonces considered to be secure in general?

Is it possible to create a secure SSL'ed API that authenticates using a session ID within a cookie, includes a nonce as a query parameter, and always responds with a JSON 'Object' response? How effective would this be against XSRF attacks? ...

What causes the hex encoded representation of a byte array to differ from the byte array itself when converted back to a byte array object?

This inquiry stems from a place of curiosity rather than any pressing need. Recently, I came across a code snippet that purportedly converts an object to a byte array (which I believed I needed at the time). While using commons-codec for this purpose, I o ...

Retrieve the Checked Value of a Checkbox Using Ajax Post in MVC

Can anyone provide assistance? This is the code I am working with: Index.cshtml <!DOCTYPE html> <html> <head> <title>jQuery With Example</title> @Scripts.Render("~/bundles/jquery") <script type="text/javascri ...

remove all clicks from jQuery queue

I am facing an issue with a click event that triggers other click events, resulting in the addition of elements to the DOM. EDIT: However, upon clicking it multiple times, additional elements are added each time. Checking the jQuery queue confirms that an ...

Verify if an interval is currently active and vice versa

My web app has basic authentication implemented. When I log in, an interval is set up like this: $("#login").click(function(e) { var interval = setInterval(function(){myFunction();}, 2000); }); However, when I log out, the interval should stop: $("#lo ...

Using regular expressions, replace all instances of " " with ' ' based on certain conditions

I am looking to replace quotes "" with single quotes '' within a string. string = `bike "car" bus "'airplane'" "bike" "'train'"` If a word is inside double quotes, it shoul ...

Do only the imported functions in a React App contribute to the overall size and overhead for the user?

For instance, my React application relies on the MUI package. However, I am only utilizing the Slider and AutoComplete components from the package. Do only these 2 components impact the performance of my application for the end user? Or does the entire p ...

Implementing Basic List Display in Vue with index identification and prop usage

As I start my todo list, I have set up an array state() { return { news: [ { id: 1, title: "Title 1", text: "Example text 1" ...

Developing a Customized Filtering Mechanism in Angular 8

I have some experience working in web development, but I am relatively new to Angular. My current project involves creating a simple filter for a table's column based on user input. However, I'm facing an issue where typing in a single letter fil ...

``Look at that cool feature - a stationary header and footer that stay in place

I'm seeking advice on how to design a website with a fixed header and footer that remain consistent across all pages, with only the content area altering. I've come across a site as an example - , but couldn't figure out how it was done even ...

How can I retrieve the data passed in a post request using Azure Functions and JavaScript?

I have a JavaScript Azure function that takes a context and request as parameters: function(context, req) It's easy to retrieve data from a GET request using the req object. For example, if I pass name=test in the URL, I can retrieve it in my code l ...

Utilize JQuery to display a modal dialog within a pre-existing modal dialog

In my project, I am currently utilizing JQuery version 2.1.1 and JQuery UI version 1.11.0. My aim is to open a modal dialog within another modal dialog, with the primary (parent) dialog being disabled. While both dialogs have their modal properties set to ...

Converting a string to JSON format with JavaScript

My string is structured in JSON format like this: "{""c1"": ""value1"", ""c2"": ""value2""}" After storing it in an SQLITE database, I use the following Javascript code to retrieve it back as JSON: var req= "SELECT json_column from my_table"; var re ...

Managing various encoding methods when retrieving the XML data feed

I'm attempting to access the feed from the following URL: http://www.chinanews.com/rss/scroll-news.xml using the request module. However, the content I receive appears garbled with characters like ʷ)(й)޹. Upon inspecting the XML, I noticed that ...

Personalized search feature for Bootstrap tables

Below is the table structure: <table> <tr> <th>Number</th> <th>Name</th> </tr> <tr> <td>200.10.1234</td> <td>Maria Anders</td> </tr> <tr> < ...

Step-by-step guide to creating a perforated container:

I'm putting together a step-by-step guide on how to navigate through my app for the first time. Imagine a pop-up that explains how to use a specific button During the tutorial, I envision a darkened background with a highlighted circle around the bu ...

Are there any JQuery events that can detect alterations in the list of children elements within an element?

Is there a JQuery event available that can detect changes in the size of an element collection, such as growth or reduction resulting from adding or removing child elements? ...

Is there a way to generate a SVG path connecting various DIV elements programmatically?

How can I achieve a dynamic SVG path between my word DIVs? This is my current progress and this is my desired outcome. Could you please explain why my code isn't working as expected? I attempted to calculate the XY positions of my words to create an ...