0

We can just simply use array.sort() (the array contains alphabets), but that will sort the whole array. But I just want to sort a part of the array like this:

Lets assume array = ["c" , "d" , "b" , "f" , "a" , "e"]. Now, instead of sorting it completely, I want to sort it from index 2 to 5 , so array becomes ["c" , "d" , "a" , "b" , "e" , "f"].

Is there any method in Array.prototype to do this?

NOTE: I can write a custom function to solve this problem, but I am avoiding it. Maybe I could just get a quick solution...

3
  • Is there any method in Array.prototype to do this? NO! Commented Mar 29, 2016 at 12:57
  • there is nothing built in like that. Commented Mar 29, 2016 at 12:57
  • There is nothing built in like you desire in the current array prototypes list, the closest you can get if you don't want to write your own function (any reason to avoid doing such?) is to splice the array and, then, to concatenate it back once sorted (you can even do that inline if you are writing the array by your own). What I'm surprised about, though, is that there seems to be no logic about sorting just some elements of the array. Commented Mar 29, 2016 at 13:11

4 Answers 4

1

There is no function available that does exactly what you asked.

To achieve what you want, you'll have to do something like the following:

var array = ["c", "d", "b", "f", "a", "e"];
var array1 = array.splice(2, 4);

array1.sort();

array = array.concat(array1);

console.log(array);

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

1 Comment

@Jai - Apart from a typo mistake (already rectified), do you have any questions?
0

Try this

    var arr = ["c" , "d" , "b" , "f" , "a" , "e"];
    var tmpArr = arr.slice(2,5);
    tmpArr.sort();
    arr = arr.slice(0,2).concat(tmpArr).concat(arr.slice(5));

 document.body.innerHTML += JSON.stringify(arr,0,4);

Comments

0

The full list of Array prototype methods is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype.

The nearest thing I could find to what you want would be to use Array.slice to get 3 arrays: the elements before those you want to sort, the elements you want to sort and the elements after those you want to sort. Then use Array.sort to sort the desired elements. Finally glue the arrays back together with Array.concat.

Comments

0

.slice() will be good choice:

var arr = ["c" , "d" , "b" , "f" , "a" , "e"];
var o = arr.slice(0, 2); // take the first two out
var a = arr.slice(-4).sort(); // now slice back and sort it

var n = o.concat(a); // concat the two arrarys and return it.

document.querySelector('pre').innerHTML = JSON.stringify(n, 0, 0);
<pre></pre>

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.