Cihat Şaman
Cihat Şaman

Reputation: 4814

How to sort an array of words' length correctly with for loop?

I tried to sort the words' length of a string via for loop. Yes, I can do it with sort method easily, but want to try with just a for loop. I think I am missing something...

function findLongestWordLength(str) {
  let regex = /\w+-\w+|\w+/g;
  let result = str.match(regex);
  let arr = [];
  let arr2 = [];

  for (let i = 0; i < result.length; i++) {
    arr.push(result[i].length);
  }

  const orderSmallerToBig = arr.sort(function (a, b) {
    return a - b;
  });

  for (let i = 0; i < result.length; i++) {
    arr2.push(result[i].length);
  }
  console.log(arr2);
  console.log(orderSmallerToBig);
  console.log(result);

  for (let i = 0; i < arr.length; i++) {
    for (let j = i; j < arr.length; j++) {
      if (orderSmallerToBig[i] == arr2[j]) {
        result[i] = result[j];

        console.log({ i, j });
        j = arr2.length;
      }
    }
  }

  console.log(result);
}

console.log(
  findLongestWordLength(
    "What if we try a super-long word such as otorhinolaryngology"
  )
);


Output should be like that:

["a", "if", "we", "as", "try", "What", "long", "word", "such", "super", "otorhinolaryngology"]

Upvotes: 0

Views: 356

Answers (1)

KarthikNayak98
KarthikNayak98

Reputation: 363

let st = "What if we try a super-long word such as otorhinolaryngology"

let inputArr = st.split(/[\s-]+/);


function string_sort(inputArr) {
  let len = inputArr.length;
  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len - i - 1; j++) {
      if (inputArr[j].length > inputArr[j + 1].length) {
        let tmp = inputArr[j];
        inputArr[j] = inputArr[j + 1];
        inputArr[j + 1] = tmp;
      }
    }
  }
  return inputArr;
}
arr = string_sort(inputArr);

console.log(arr);

Try this code. I have used bubble sort for sorting based on length.

Upvotes: 1

Related Questions