w3resource

JavaScript: Check if an array is a factor chain

JavaScript Array: Exercise-51 with Solution

Write a JavaScript program to check if an array is a factor chain or not.

A factor chain is an array in which the previous element is a factor of the next consecutive element. The following is a factor chain:
[2, 4, 8, 16, 32]
// 2 is a factor of 4
// 4 is a factor of 8
// 8 is a factor of 16
// 16 is a factor of 32

Test Data:

([2, 4, 8, 16, 32]) -> true
([2, 4, 16, 32, 64]) -> true
([2, 4, 16, 32, 68]) -> false

Sample Solution:

JavaScript Code :

// Function to check if an array forms a factor chain
function test(nums) { 
  // Iterate through the array elements up to the second-to-last element
  for (var i = 0; i < nums.length - 1; i++) 
  {
    // Check if the next element is not a factor of the current element
    if (nums[i + 1] % nums[i] != 0) {
      // If not, the array does not form a factor chain
      return false;            
    }
  }
  
  // If the loop completes without returning, the array forms a factor chain
  return true;
}

// Test the function with an array that forms a factor chain
nums = [2, 4, 8, 16, 32];
console.log("Original array: ", nums);
console.log("Check the said array is a factor chain or not?");
console.log(test(nums));

// Test the function with another array that forms a factor chain
nums = [2, 4, 16, 32, 64];
console.log("Original array: ", nums);
console.log("Check the said array is a factor chain or not?");
console.log(test(nums));

// Test the function with an array that does not form a factor chain
nums = [2, 4, 16, 32, 68];
console.log("Original array: ", nums);
console.log("Check the said array is a factor chain or not?");
console.log(test(nums));

Output:

Original array: 
Check the said array is a factor chain or not?
true
Original array: 
Check the said array is a factor chain or not?
true
Original array: 
Check the said array is a factor chain or not?
false

Flowchart :

JavaScript array flowchart: Check if an array is a factor chain.

Live Demo :

See the Pen javascript-array-exercise-51 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous:Sum all numbers of an array of mixed data types.
Next: Find all indexes of NaN in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-array-exercise-51.php