3

I was writing a function to extract the index of the word which is included in a word, For example : 4of Fo1r pe6ople g3ood th5e the2 This should align order wise, Below is the code,

function order(words){
    var result = []
    var sorting = words.split(' ').sort() 
    console.log(sorting);
    for(let i=0; i<sorting.length;i++)
    {
      var temp = sorting[i].split('').sort()//By this the words in the sentence get sorted and i will get the index(number) of the corresponding word at first position.
      console.log(temp);
      var valueHolder = parseInt(temp) //I will take the above obtained value and convert it into integer
        console.log(valueHolder);
      result.splice((valueHolder-1),0,sorting[i]) //will pass the index here
    }
    console.log(result);
  }

But i am getting the wrong output : [ 'Fo1r', 'the2', '4of', 'g3ood', 'pe6ople', 'th5e' ] Did i miss anything, Can anyone help me with this Thanks. Above array.splice(index,0,item) will just insert the element at the specified position, and with 0

Expected output is : [ 'Fo1r', 'the2', 'g3ood', '4of', 'th5e','pe6ople' ]

2
  • sorting[i].split('').sort() produces an array of characters if i dont get it wrong, which is stored in temp. How can that be used as an argument to parseInt?? Commented Apr 30, 2021 at 7:18
  • @TostMaster I have purposefully given that, since temp always gives the initial index value, as I have used the sort, so all the numbers are now aligned, by using temp, the default value we will get as the initial index item so I can get the real index then convert it into integer Commented Apr 30, 2021 at 17:09

4 Answers 4

2

You can use an regex then you can parse numbers above 9.

the regex const r = /\d+/; looks for one or more digits. Then the regex is used in the sorting method a.match(r) and the resulting number is then parsed and compared.

const str = '4of Fo1r pe6ople g3ood th5e no71w the2';

function order(words) {
  let result = [];
  let sorting = words.split(' ');
  const r = /\d+/;
  
  sorting.sort((a,b) => {
    return parseInt(a.match(r)) - parseInt(b.match(r));
  });
  console.log(sorting.join(' '));
}
order(str);

Sign up to request clarification or add additional context in comments.

1 Comment

@NilsKhaler, Thanks man this also really works fine
1

Problem was that your result array initial size is not set, so splicing will not work correctly during the loop.

Easy fix:

words='4of Fo1r pe6ople g3ood th5e the2';

function order(words){
    var result = []
    var sorting = words.split(' '); 
    var result = new Array(sorting.length);
    console.log(result)
    for(let i=0; i<sorting.length;i++)
    {
      var temp = sorting[i].split('').sort()//By this the words in the sentence get sorted and i will get the index(number) of the corresponding word at first position.
      //console.log(temp);
      var valueHolder = parseInt(temp) //I will take the above obtained value and convert it into integer
        //console.log(valueHolder);
    result.splice(valueHolder-1,1,sorting[i]) //will pass the index here
   
    }
    console.log(result);
  }
  
order(words)

words='4of Fo1r pe6ople g3ood th5e the2';

function order(words){
    var result = []
    var sorting = words.split(' '); 
    var result = new Array(sorting.length);
   // console.log(result)
    for(let i=0; i<sorting.length;i++)
    {
      var temp = sorting[i].split('').sort()//By this the words in the sentence get sorted and i will get the index(number) of the corresponding word at first position.
      //console.log(temp);
      var valueHolder = parseInt(temp) //I will take the above obtained value and convert it into integer
        //console.log(valueHolder);
    result.splice(valueHolder-1,1,sorting[i]) //will pass the index here
   
    }
    console.log(result);
  }
  
order(words)

Comments

1

Array#splice is not the correct thing that you should be using here, instead use indexing to add elements to the desired location.

function order(words) {
  var result = [];
  var sorting = words.split(" ").sort();
  for (let i = 0; i < sorting.length; i++) {
    var temp = sorting[i].split("").sort();
    var valueHolder = parseInt(temp);
    result[valueHolder - 1] = sorting[i];
  }
  console.log(result);
}

order("4of Fo1r pe6ople g3ood th5e the2");

1 Comment

@Aravinda KS Please check if this solves your problem, do let me know if you have any issues.
1

This will work in all the scenarios. Less and Simplest code using regex.

Solution

 function order(string) {
   var regex = /\d+/g;
   var matches = string.match(regex);        
   matches.sort(function(a, b){return parseInt(a)-parseInt(b)});

   var splittedArr = string.split(' ');

   var result = [];
   matches.forEach(item => {
      const findItem = splittedArr.find(a => a.includes(item));
      result.push(findItem);
   })
   console.log(result)
}

order('4of Fo1r pe6ople g3ood th5e the2') // your string
order('77of Fo1r pe6ople g3ood th8e the2') // other string
order('0of Fo1r pe6ople g4ood th8e the2') // other string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.