Picking the triangle edges with maximum perimeter JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

The perimeter of a triangle is the sum of all three sides of the triangle. We are required to write a JavaScript function that takes in an array of numbers of at least three or more elements.

Our function should pick three longest sides (largest numbers) from the array that when summed can give the maximum perimeter from the array, we need to make sure that the three picked side can make a triangle in reality. If three exists no three sides in the array that can make a valid triangle, then we have to return zero.

A valid triangle is that triangle in which the sum of any two sides is always greater than the third side.


const arr = [1, 2, 3, 5, 6, 7, 9];
const largestPerimeter = (arr = []) => {
   arr.sort((a, b) => a - b);
   let max = 0;
   for (let i = arr.length - 1; i >= 2; i--) {
      let start = i - 2;
      let end = i - 1;
      while (start < end) {
         if (arr[end] + arr[start] > arr[i]) {
            return arr[end] + arr[start] + arr[i];
         else {
   return 0;


And the output in the console will be −

Published on 23-Nov-2020 11:08:54