TransWikia.com

Check if the next item is 1 unit longer (Javascript)

Stack Overflow Asked by Ekhi Arzac on December 11, 2021

I am a coding beginner and I was writing the following function that checks if the next string of a given array is one unit longer:

function canBuild(arr) {
    for(let i = 0; i < arr.length; i++) {
        if (i == arr.length-1) { return true }
        if (arr[i].length+1 != arr[i+1].length) { return false }
    }
}

desired output:

canBuild(["a", "at", "ate", "late", "plate", "plates"]) ➞ true

canBuild(["it", "bit", "bite", "biters"]) ➞ false

// "biters" is 2 units longer than the previous string

I was wondering if there is a more efficient and shorter way to write the same function, if someone explained me other ways to do so I would really appreciate it!

3 Answers

Use every method and some temp variable (x here)

const canBuild = (arr) => (
  (x = arr[0]?.length), arr.every((c) => c.length === x++)
);

console.log(canBuild(["a", "at", "ate", "late", "plate", "plates"]));

console.log(canBuild(["it", "bit", "bite", "biters"]));

Answered by Siva K V on December 11, 2021

   function canBuild(arr) {
        for(let i = 0; i < arr.length; i++) {
            if(i > 0 && arr[i].length !== arr[i-1].length+1)
               return false;
        }
        return true;
    }

EDIT: even better, as suggeste by Thomas:

     function canBuild(arr) {
        for(let i = 1; i < arr.length; i++) {
            if(arr[i].length !== arr[i-1].length+1)
               return false;
        }
        return true;
    }

Answered by gbalduzzi on December 11, 2021

function canBuild(arr) {
        for(let i = 0; i < arr.length; i++) {
            if(i+1 != arr[i].length)
               return false;
        }
        return true;
    }

This is a O(n) solution.

Answered by Ashish Mishra on December 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP