Determine whether the values in the array are arranged in ascending or descending order

I'm currently working on a code problem where I need to loop over the values of an array and determine whether they are in ascending order, descending order, or neither. The function I've written so far is not giving me the correct results, but I am determined to figure out what's wrong with it.

While I have seen another approach to solving this problem, I believe that my current logic is heading in the right direction. As a learner, I want to continue exploring my own solution before resorting to alternatives. Thank you for your help!

function ascDscArray(array) {
    for (var i = 1; i < array.length - 1; i++) {
        if (array[i - 1] < array[i]) return "yes, ascending";
        if (array[i - 1] > array[i]) return "yes, descending";
        else return "no";
    }
}

Just a heads up: I'm trying to test this function with two example arrays: [15, 7, 3, -8] and [4, 2, 30].

Answer №1

To efficiently check the order of elements in an array, you can implement a comparison function and utilize the Array#every method with a short-circuit optimization. This approach compares each element with its preceding one to determine if they follow the expected order.

The function will return either the type of ordering (ascending or descending) or indicate if the array is not ordered at all.

function checkOrder(array) {
    var direction = array[0] < array[1]
            ? { type: 'asc', fn: (a, b) => a < b }
            : { type: 'desc', fn: (a, b) => a > b };

    return array.every((v, i, a) => !i || direction.fn(a[i - 1], v))
        ? direction.type
        : 'no';
}

console.log([[15, 7, 3, -8], [4, 2, 30], [1, 2, 3]].map(checkOrder));

An alternative version employs two variables to track ascending and descending orders separately by comparing the first element with all subsequent ones.

If both variables remain true after iteration, the function returns 'no'; otherwise, it returns the detected order.

Note: This method iterates through all elements in the array.

function detectAscDesc(array) {
    var asc = false, desc = false;
    for (var i = 1; i < array.length; i++) {
        if (array[0] < array[i]) {
            asc = true;
        }
        if (array[0] > array[i]) {
            desc = true;
        }      
    }
    if (asc && desc) return 'no';
    return asc ? 'asc' : 'desc';
}

console.log([[15, 7, 3, -8], [4, 2, 30], [1, 2, 3]].map(detectAscDesc));

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

JQuery's addClass function is not functioning properly

Check out the code snippet below: function toggleAccessRequests() { var buttonValue = $("#showAccessRequests").val(); if (buttonValue == "Show") { $(".hideAccessRequest").removeClass("hideAccessRequest"); $("#showAccessRequests").v ...

Arrangement of elements in MongoDB

In my application, there is a list of games, each with a specific position that determines the order in which they are displayed to users (e.g. 1, 2, 3...). Currently, I am using MongoDB to store all the game data. Let's say I have a game with positi ...

Utilize the underscore symbol when iterating through an Express application

Here is a snippet of my CoffeeScript code: dirs = ["/assets", "/public", "/locales", "/data/topo"] app.configure -> app.use assets(build : true) jsPaths assets, console.log @use(express.favicon(process.cwd() + "/assets/images/favi ...

Guide to triggering an API call upon changing the value in a Vue Multiselect component

Is there a way to trigger an API call when the value changes in a Vue Multiselect component? I want to update the value in the multiselect, make an API call, and display the result in the console. Below is my code snippet. <template> <div> ...

What is the most effective method for incorporating keyframes using JavaScript in a dynamic way?

Is there a way to animate an HTML element by using a variable with keyframes, but without directly manipulating the DOM? Below is the HTML code: <div class="pawn" id="pawn1"></div> Here is the CSS keyframes code: @keyframe ...

Is it necessary to sanitize strings before assigning them as the content of a textarea element?

Consider the situation described below: var evil_string = "..."; $('#mytextarea').val(evil_string); Is it necessary to sanitize an untrusted string before setting it as the value of a textarea element? While I am aware of the importance of han ...

Tips for obtaining user input to place markers on a video timeline with JavaScript

I am new to Java script and I am trying to create a video player where users can click on the progress bar to place markers. Can you please review my code below and let me know if there are any errors? index.html <!doctype html> <html> <he ...

Unravel complex JSON arrays in PHP with multiple dimensions

I am struggling to decode a JSON array and make it readable without receiving an error. My desired output should look like this: image1 image2 image3 $json = ' { "acf" : { "hero_banner" : [ { "banner_image" : ...

Guide to converting raw Mysql fields into objects using Node.js

I have written a code to retrieve all the rows from the article table in MySQL, but I would like to represent this data in object and array format so that I can send it to endpoints. app.get('/article' , function(req , res){ var connec ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

Determining the appropriate width based on the length and style of text

Imagine you possess <span class='class'>gfdsdfgfdsg</span> Is there a way to determine the exact size in pixels that I need for it before rendering? (I'm not looking for automatic adjustment, just a calculation.) ...

Ways to conceal the scroll bar upon the initial loading of a webpage

Recently, I created a single-page website consisting of 4 sections. The client has specific requirements that need to be fulfilled: The scrollbar should not be visible when the page loads. Once the user starts scrolling past the second section, the scrol ...

On a live server, the Bootstrap modal fails to function as intended

Trigger Button: while ($row = mysqli_fetch_array($result)) { $name = $row['name']; $id = $row['id']; echo '<a data-target="#exampleModal" class="wpmui-field-input button wpmui-submit button-primary" data ...

Is there a way to retrieve the value of a dropped file in a file input using jQuery?

Can the data from a dropped file be set in a file upload input field? Or does a dropped file need to be instantly uploaded to the server? Here is an example code snippet: <input type="file" id="drop-box" /> $("#drop-box").on('drop', fun ...

Data binding in Vue.js seems to be malfunctioning

I'm having trouble with my Vue component creation. I've been using v-show to hide certain elements, but it doesn't seem to be working as intended. The goal is to hide an element when clicked from a list by setting element.visible to false i ...

Substitute the main node with the subordinate node within a json file

Here is a JSON object structure: { "coach": { "Errors": { "items": [ { "errorMessage": "You must select a date that is in the future.", "errorBOPath": "twl.date" ...

What is the best way to save newly added elements on a webpage that were submitted by the

I am looking for a way to save the changes made by users on my webpage so that they can navigate to different pages and come back without losing any added elements. These changes should be retained even when the user goes back to edit the webpage, but I pr ...

Is there a way to ensure that both new Date() and new Date("yyyy-mm-dd hh:mm:ss") are initialized with the same timezone?

When utilizing both constructors, I noticed that they generate with different timezones. Ideally, they should be in the same timezone to ensure accurate calculations between them. I attempted to manually parse today's date and time, but this feels li ...

Why is JSON ParseError still returned by jQuery .ajax call despite JSON being seemingly correct?

Despite having valid JSON on jsonlint.com, I'm encountering a ParseError. Below is the jQuery code snippet: $.ajax({ url: path, type: 'GET', data: {}, cache: false, dataType: 'json', contentType: 'app ...

Displaying items using a filter function in ng-repeat

I am facing an issue with using a filter on my ng-repeat that involves a function with a parameter passed in, but for some reason, the filter is not working as expected. The function I am using for the filter compares two arrays to find any matching eleme ...