Aravinda KS
Aravinda KS

Reputation: 195

Logical error! in Array insertion at specified position using strings

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' ]

Upvotes: 3

Views: 67

Answers (4)

Nils K&#228;hler
Nils K&#228;hler

Reputation: 3001

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);

Upvotes: 2

Surjeet Bhadauriya
Surjeet Bhadauriya

Reputation: 7156

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

Upvotes: 1

sinisake
sinisake

Reputation: 11328

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)

Upvotes: 1

Som Shekhar Mukherjee
Som Shekhar Mukherjee

Reputation: 8168

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");

Upvotes: 1

Related Questions