Computer >> Computer tutorials >  >> Programming >> Javascript

Checking progressive array - JavaScript


We are required to write a JavaScript function that takes in an array of strings, ordered by ascending length.

The function should return true if, for each pair of consecutive strings, the second string can be formed from the first by adding a single letter either at the beginning or end.

For example: If the array is given by −

const arr = ["c", "ca", "can", "acan", "acane", "dacane"];

Then our function should return true.

Example

Following is the code −

const arr = ["c", "ca", "can", "acan", "acane", "dacane"];
const isProgressive = arr => {
   for(let i = 0; i < arr.length-1; i++){
      const nextLength = arr[i+1].length;
      if(arr[i+1] === arr[i+1][0] + arr[i] || arr[i+1] === arr[i] +
      arr[i+1][nextLength-1] ){
         continue;
      };
      return false;
   };
   return true;
};
console.log(isProgressive(arr));

Output

Following is the output in the console −

true