How to sort elements in array without changing other elements indexes?
I have this array:
var arr = [5, 3, 2, 8, 1, 4];
I'm trying to sort ONLY the elements that are odd values so I want this
output:
[1, 3, 2, 8, 5, 4]
As you can see the even elements don't change their position. Can anyone tell me what I'm missing? Here's my code:
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0){
arr.push(val);
}
return arr.sort();
}, );
return oddElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4]));
I know I can use slice to add elements to array, but I'm stuck on how to get the indexes and put the elements in the array.
javascript
add a comment |
I have this array:
var arr = [5, 3, 2, 8, 1, 4];
I'm trying to sort ONLY the elements that are odd values so I want this
output:
[1, 3, 2, 8, 5, 4]
As you can see the even elements don't change their position. Can anyone tell me what I'm missing? Here's my code:
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0){
arr.push(val);
}
return arr.sort();
}, );
return oddElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4]));
I know I can use slice to add elements to array, but I'm stuck on how to get the indexes and put the elements in the array.
javascript
add a comment |
I have this array:
var arr = [5, 3, 2, 8, 1, 4];
I'm trying to sort ONLY the elements that are odd values so I want this
output:
[1, 3, 2, 8, 5, 4]
As you can see the even elements don't change their position. Can anyone tell me what I'm missing? Here's my code:
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0){
arr.push(val);
}
return arr.sort();
}, );
return oddElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4]));
I know I can use slice to add elements to array, but I'm stuck on how to get the indexes and put the elements in the array.
javascript
I have this array:
var arr = [5, 3, 2, 8, 1, 4];
I'm trying to sort ONLY the elements that are odd values so I want this
output:
[1, 3, 2, 8, 5, 4]
As you can see the even elements don't change their position. Can anyone tell me what I'm missing? Here's my code:
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0){
arr.push(val);
}
return arr.sort();
}, );
return oddElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4]));
I know I can use slice to add elements to array, but I'm stuck on how to get the indexes and put the elements in the array.
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0){
arr.push(val);
}
return arr.sort();
}, );
return oddElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4]));
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0){
arr.push(val);
}
return arr.sort();
}, );
return oddElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4]));
javascript
javascript
edited 1 hour ago
progx
asked 1 hour ago
progxprogx
309521
309521
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
First sort only the odd numbers and put it in an array oddSorted
. Then map
through each element in the original array and check if the current element is odd, if odd replace it with the corresponding sorted number from the oddSorted
array.
function sortOddElements(arr){
var temp = [...arr];
var oddSorted = temp.filter(ele => ele %2 != 0).sort((a, b) => a - b);
var evenNotSorted = arr.map((ele, idx) => {
if(ele % 2 != 0){
return oddSorted.shift();
}
return ele;
});
return evenNotSorted;
}
var arr = [5, 3, 2, 8, 1, 4];
console.log(sortOddElements(arr));
arr = [5, 3, 2, 8, 1, 4, 11 ];
console.log(sortOddElements(arr));
easy-to-follow answer. now, can you think of a way to do this without having to do the% 2 != 0
calculation twice per element? :D
– user633183
33 mins ago
One thing that comes to my mind is checking whether the current element is included in theoddSorted
array, if yes then replace the current number with the first number from theoddSorted
array. This will also work as if the current element is included in theoddSorted
array then it implies that the number is odd and hence there is no need to check it again. But do you think this will improve the performance?
– Amardeep Bhowmick
23 mins ago
add a comment |
One option is to keep track of the indicies of the odd numbers in the original array, and after .reduce
ing and sorting, then iterate through the original odd indicies and reassign, taking from the sorted odd array:
function oddSort(array) {
const oddIndicies = ;
const newArr = array.slice();
const sortedOdd = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
oddIndicies.push(index);
}
return arr;
}, )
.sort((a, b) => a - b);
while (oddIndicies.length > 0) {
newArr[oddIndicies.shift()] = sortedOdd.shift();
}
return newArr;
}
console.log(oddSort([5, 3, 2, 8, 1, 4]));
console.log(oddSort([5, 3, 2, 8, 1, 4, 11 ]));
your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
1 hour ago
Ah, the 11 was throwing things off, since.sort
sorts lexiographically - use a custom.sort
function instead, see edit
– CertainPerformance
58 mins ago
add a comment |
I modified your code a little bit to fulfill your objective. Take a look below
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
}
return arr.sort(function(a, b){return a - b});
}, );
var index = 0;
var finalElements = ;
for(var i=0; i<array.length; i++) {
var element = array[i];
if(element %2 !==0) {
finalElements.push(oddElements[index]);
index++;
} else {
finalElements.push(element);
}
}
return finalElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4, 11]));
Remember, the default sort function sorts the values alphabetically. That's why you can't just use arr.sort()
Nope, your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
58 mins ago
Okay... I'm taking a look at it
– Tanmoy Krishna Das
58 mins ago
The problem was with the sort function. The default sort function sorts the values alphabetically. That's why you can't just use arr.sort(). I modified the code to reflect your needs.
– Tanmoy Krishna Das
50 mins ago
add a comment |
Fun problem, thanks for sharing! I think this is a straightforward approach -
const compare = (a, b) =>
a < b ? -1
: a > b ? 1
: 0
const main = (arr) =>
{ const odds =
const idxs =
for (const [ i, x ] of arr.entries())
if (x & 1)
(odds.push(x), idxs.push(i))
// odds = [ 5, 3, 11, 1 ]
// idxs = [ 0, 1, 4, 6 ]
odds.sort(compare)
// no need to sort idxs, always inserted in order
// odds = [ 1, 3, 5, 11 ]
// idxs = [ 0, 1, 4, 6 ]
for (const [ i, x ] of odds.entries())
arr[idxs[i]] = x
return arr
}
console.log(main([ 5, 3, 2, 8, 11, 4, 1 ]))
// [ 1, 3, 2, 8, 5, 4, 11 ]
If you want main
to be an immutable operation, change the end to
const result = [ ...arr ]
for (const [ i, x ] of odds.entries())
result[idxs[i]] = x
return result
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54264468%2fhow-to-sort-elements-in-array-without-changing-other-elements-indexes%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
First sort only the odd numbers and put it in an array oddSorted
. Then map
through each element in the original array and check if the current element is odd, if odd replace it with the corresponding sorted number from the oddSorted
array.
function sortOddElements(arr){
var temp = [...arr];
var oddSorted = temp.filter(ele => ele %2 != 0).sort((a, b) => a - b);
var evenNotSorted = arr.map((ele, idx) => {
if(ele % 2 != 0){
return oddSorted.shift();
}
return ele;
});
return evenNotSorted;
}
var arr = [5, 3, 2, 8, 1, 4];
console.log(sortOddElements(arr));
arr = [5, 3, 2, 8, 1, 4, 11 ];
console.log(sortOddElements(arr));
easy-to-follow answer. now, can you think of a way to do this without having to do the% 2 != 0
calculation twice per element? :D
– user633183
33 mins ago
One thing that comes to my mind is checking whether the current element is included in theoddSorted
array, if yes then replace the current number with the first number from theoddSorted
array. This will also work as if the current element is included in theoddSorted
array then it implies that the number is odd and hence there is no need to check it again. But do you think this will improve the performance?
– Amardeep Bhowmick
23 mins ago
add a comment |
First sort only the odd numbers and put it in an array oddSorted
. Then map
through each element in the original array and check if the current element is odd, if odd replace it with the corresponding sorted number from the oddSorted
array.
function sortOddElements(arr){
var temp = [...arr];
var oddSorted = temp.filter(ele => ele %2 != 0).sort((a, b) => a - b);
var evenNotSorted = arr.map((ele, idx) => {
if(ele % 2 != 0){
return oddSorted.shift();
}
return ele;
});
return evenNotSorted;
}
var arr = [5, 3, 2, 8, 1, 4];
console.log(sortOddElements(arr));
arr = [5, 3, 2, 8, 1, 4, 11 ];
console.log(sortOddElements(arr));
easy-to-follow answer. now, can you think of a way to do this without having to do the% 2 != 0
calculation twice per element? :D
– user633183
33 mins ago
One thing that comes to my mind is checking whether the current element is included in theoddSorted
array, if yes then replace the current number with the first number from theoddSorted
array. This will also work as if the current element is included in theoddSorted
array then it implies that the number is odd and hence there is no need to check it again. But do you think this will improve the performance?
– Amardeep Bhowmick
23 mins ago
add a comment |
First sort only the odd numbers and put it in an array oddSorted
. Then map
through each element in the original array and check if the current element is odd, if odd replace it with the corresponding sorted number from the oddSorted
array.
function sortOddElements(arr){
var temp = [...arr];
var oddSorted = temp.filter(ele => ele %2 != 0).sort((a, b) => a - b);
var evenNotSorted = arr.map((ele, idx) => {
if(ele % 2 != 0){
return oddSorted.shift();
}
return ele;
});
return evenNotSorted;
}
var arr = [5, 3, 2, 8, 1, 4];
console.log(sortOddElements(arr));
arr = [5, 3, 2, 8, 1, 4, 11 ];
console.log(sortOddElements(arr));
First sort only the odd numbers and put it in an array oddSorted
. Then map
through each element in the original array and check if the current element is odd, if odd replace it with the corresponding sorted number from the oddSorted
array.
function sortOddElements(arr){
var temp = [...arr];
var oddSorted = temp.filter(ele => ele %2 != 0).sort((a, b) => a - b);
var evenNotSorted = arr.map((ele, idx) => {
if(ele % 2 != 0){
return oddSorted.shift();
}
return ele;
});
return evenNotSorted;
}
var arr = [5, 3, 2, 8, 1, 4];
console.log(sortOddElements(arr));
arr = [5, 3, 2, 8, 1, 4, 11 ];
console.log(sortOddElements(arr));
function sortOddElements(arr){
var temp = [...arr];
var oddSorted = temp.filter(ele => ele %2 != 0).sort((a, b) => a - b);
var evenNotSorted = arr.map((ele, idx) => {
if(ele % 2 != 0){
return oddSorted.shift();
}
return ele;
});
return evenNotSorted;
}
var arr = [5, 3, 2, 8, 1, 4];
console.log(sortOddElements(arr));
arr = [5, 3, 2, 8, 1, 4, 11 ];
console.log(sortOddElements(arr));
function sortOddElements(arr){
var temp = [...arr];
var oddSorted = temp.filter(ele => ele %2 != 0).sort((a, b) => a - b);
var evenNotSorted = arr.map((ele, idx) => {
if(ele % 2 != 0){
return oddSorted.shift();
}
return ele;
});
return evenNotSorted;
}
var arr = [5, 3, 2, 8, 1, 4];
console.log(sortOddElements(arr));
arr = [5, 3, 2, 8, 1, 4, 11 ];
console.log(sortOddElements(arr));
edited 30 mins ago
answered 38 mins ago
Amardeep BhowmickAmardeep Bhowmick
1,7521821
1,7521821
easy-to-follow answer. now, can you think of a way to do this without having to do the% 2 != 0
calculation twice per element? :D
– user633183
33 mins ago
One thing that comes to my mind is checking whether the current element is included in theoddSorted
array, if yes then replace the current number with the first number from theoddSorted
array. This will also work as if the current element is included in theoddSorted
array then it implies that the number is odd and hence there is no need to check it again. But do you think this will improve the performance?
– Amardeep Bhowmick
23 mins ago
add a comment |
easy-to-follow answer. now, can you think of a way to do this without having to do the% 2 != 0
calculation twice per element? :D
– user633183
33 mins ago
One thing that comes to my mind is checking whether the current element is included in theoddSorted
array, if yes then replace the current number with the first number from theoddSorted
array. This will also work as if the current element is included in theoddSorted
array then it implies that the number is odd and hence there is no need to check it again. But do you think this will improve the performance?
– Amardeep Bhowmick
23 mins ago
easy-to-follow answer. now, can you think of a way to do this without having to do the
% 2 != 0
calculation twice per element? :D– user633183
33 mins ago
easy-to-follow answer. now, can you think of a way to do this without having to do the
% 2 != 0
calculation twice per element? :D– user633183
33 mins ago
One thing that comes to my mind is checking whether the current element is included in the
oddSorted
array, if yes then replace the current number with the first number from the oddSorted
array. This will also work as if the current element is included in the oddSorted
array then it implies that the number is odd and hence there is no need to check it again. But do you think this will improve the performance?– Amardeep Bhowmick
23 mins ago
One thing that comes to my mind is checking whether the current element is included in the
oddSorted
array, if yes then replace the current number with the first number from the oddSorted
array. This will also work as if the current element is included in the oddSorted
array then it implies that the number is odd and hence there is no need to check it again. But do you think this will improve the performance?– Amardeep Bhowmick
23 mins ago
add a comment |
One option is to keep track of the indicies of the odd numbers in the original array, and after .reduce
ing and sorting, then iterate through the original odd indicies and reassign, taking from the sorted odd array:
function oddSort(array) {
const oddIndicies = ;
const newArr = array.slice();
const sortedOdd = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
oddIndicies.push(index);
}
return arr;
}, )
.sort((a, b) => a - b);
while (oddIndicies.length > 0) {
newArr[oddIndicies.shift()] = sortedOdd.shift();
}
return newArr;
}
console.log(oddSort([5, 3, 2, 8, 1, 4]));
console.log(oddSort([5, 3, 2, 8, 1, 4, 11 ]));
your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
1 hour ago
Ah, the 11 was throwing things off, since.sort
sorts lexiographically - use a custom.sort
function instead, see edit
– CertainPerformance
58 mins ago
add a comment |
One option is to keep track of the indicies of the odd numbers in the original array, and after .reduce
ing and sorting, then iterate through the original odd indicies and reassign, taking from the sorted odd array:
function oddSort(array) {
const oddIndicies = ;
const newArr = array.slice();
const sortedOdd = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
oddIndicies.push(index);
}
return arr;
}, )
.sort((a, b) => a - b);
while (oddIndicies.length > 0) {
newArr[oddIndicies.shift()] = sortedOdd.shift();
}
return newArr;
}
console.log(oddSort([5, 3, 2, 8, 1, 4]));
console.log(oddSort([5, 3, 2, 8, 1, 4, 11 ]));
your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
1 hour ago
Ah, the 11 was throwing things off, since.sort
sorts lexiographically - use a custom.sort
function instead, see edit
– CertainPerformance
58 mins ago
add a comment |
One option is to keep track of the indicies of the odd numbers in the original array, and after .reduce
ing and sorting, then iterate through the original odd indicies and reassign, taking from the sorted odd array:
function oddSort(array) {
const oddIndicies = ;
const newArr = array.slice();
const sortedOdd = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
oddIndicies.push(index);
}
return arr;
}, )
.sort((a, b) => a - b);
while (oddIndicies.length > 0) {
newArr[oddIndicies.shift()] = sortedOdd.shift();
}
return newArr;
}
console.log(oddSort([5, 3, 2, 8, 1, 4]));
console.log(oddSort([5, 3, 2, 8, 1, 4, 11 ]));
One option is to keep track of the indicies of the odd numbers in the original array, and after .reduce
ing and sorting, then iterate through the original odd indicies and reassign, taking from the sorted odd array:
function oddSort(array) {
const oddIndicies = ;
const newArr = array.slice();
const sortedOdd = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
oddIndicies.push(index);
}
return arr;
}, )
.sort((a, b) => a - b);
while (oddIndicies.length > 0) {
newArr[oddIndicies.shift()] = sortedOdd.shift();
}
return newArr;
}
console.log(oddSort([5, 3, 2, 8, 1, 4]));
console.log(oddSort([5, 3, 2, 8, 1, 4, 11 ]));
function oddSort(array) {
const oddIndicies = ;
const newArr = array.slice();
const sortedOdd = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
oddIndicies.push(index);
}
return arr;
}, )
.sort((a, b) => a - b);
while (oddIndicies.length > 0) {
newArr[oddIndicies.shift()] = sortedOdd.shift();
}
return newArr;
}
console.log(oddSort([5, 3, 2, 8, 1, 4]));
console.log(oddSort([5, 3, 2, 8, 1, 4, 11 ]));
function oddSort(array) {
const oddIndicies = ;
const newArr = array.slice();
const sortedOdd = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
oddIndicies.push(index);
}
return arr;
}, )
.sort((a, b) => a - b);
while (oddIndicies.length > 0) {
newArr[oddIndicies.shift()] = sortedOdd.shift();
}
return newArr;
}
console.log(oddSort([5, 3, 2, 8, 1, 4]));
console.log(oddSort([5, 3, 2, 8, 1, 4, 11 ]));
edited 59 mins ago
answered 1 hour ago
CertainPerformanceCertainPerformance
80.5k143865
80.5k143865
your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
1 hour ago
Ah, the 11 was throwing things off, since.sort
sorts lexiographically - use a custom.sort
function instead, see edit
– CertainPerformance
58 mins ago
add a comment |
your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
1 hour ago
Ah, the 11 was throwing things off, since.sort
sorts lexiographically - use a custom.sort
function instead, see edit
– CertainPerformance
58 mins ago
your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
1 hour ago
your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
1 hour ago
Ah, the 11 was throwing things off, since
.sort
sorts lexiographically - use a custom .sort
function instead, see edit– CertainPerformance
58 mins ago
Ah, the 11 was throwing things off, since
.sort
sorts lexiographically - use a custom .sort
function instead, see edit– CertainPerformance
58 mins ago
add a comment |
I modified your code a little bit to fulfill your objective. Take a look below
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
}
return arr.sort(function(a, b){return a - b});
}, );
var index = 0;
var finalElements = ;
for(var i=0; i<array.length; i++) {
var element = array[i];
if(element %2 !==0) {
finalElements.push(oddElements[index]);
index++;
} else {
finalElements.push(element);
}
}
return finalElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4, 11]));
Remember, the default sort function sorts the values alphabetically. That's why you can't just use arr.sort()
Nope, your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
58 mins ago
Okay... I'm taking a look at it
– Tanmoy Krishna Das
58 mins ago
The problem was with the sort function. The default sort function sorts the values alphabetically. That's why you can't just use arr.sort(). I modified the code to reflect your needs.
– Tanmoy Krishna Das
50 mins ago
add a comment |
I modified your code a little bit to fulfill your objective. Take a look below
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
}
return arr.sort(function(a, b){return a - b});
}, );
var index = 0;
var finalElements = ;
for(var i=0; i<array.length; i++) {
var element = array[i];
if(element %2 !==0) {
finalElements.push(oddElements[index]);
index++;
} else {
finalElements.push(element);
}
}
return finalElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4, 11]));
Remember, the default sort function sorts the values alphabetically. That's why you can't just use arr.sort()
Nope, your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
58 mins ago
Okay... I'm taking a look at it
– Tanmoy Krishna Das
58 mins ago
The problem was with the sort function. The default sort function sorts the values alphabetically. That's why you can't just use arr.sort(). I modified the code to reflect your needs.
– Tanmoy Krishna Das
50 mins ago
add a comment |
I modified your code a little bit to fulfill your objective. Take a look below
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
}
return arr.sort(function(a, b){return a - b});
}, );
var index = 0;
var finalElements = ;
for(var i=0; i<array.length; i++) {
var element = array[i];
if(element %2 !==0) {
finalElements.push(oddElements[index]);
index++;
} else {
finalElements.push(element);
}
}
return finalElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4, 11]));
Remember, the default sort function sorts the values alphabetically. That's why you can't just use arr.sort()
I modified your code a little bit to fulfill your objective. Take a look below
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
}
return arr.sort(function(a, b){return a - b});
}, );
var index = 0;
var finalElements = ;
for(var i=0; i<array.length; i++) {
var element = array[i];
if(element %2 !==0) {
finalElements.push(oddElements[index]);
index++;
} else {
finalElements.push(element);
}
}
return finalElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4, 11]));
Remember, the default sort function sorts the values alphabetically. That's why you can't just use arr.sort()
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
}
return arr.sort(function(a, b){return a - b});
}, );
var index = 0;
var finalElements = ;
for(var i=0; i<array.length; i++) {
var element = array[i];
if(element %2 !==0) {
finalElements.push(oddElements[index]);
index++;
} else {
finalElements.push(element);
}
}
return finalElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4, 11]));
function myFunction(array) {
var oddElements = array.reduce((arr, val, index) => {
if (val % 2 !== 0) {
arr.push(val);
}
return arr.sort(function(a, b){return a - b});
}, );
var index = 0;
var finalElements = ;
for(var i=0; i<array.length; i++) {
var element = array[i];
if(element %2 !==0) {
finalElements.push(oddElements[index]);
index++;
} else {
finalElements.push(element);
}
}
return finalElements;
}
console.log(myFunction([5, 3, 2, 8, 1, 4, 11]));
edited 51 mins ago
answered 1 hour ago
Tanmoy Krishna DasTanmoy Krishna Das
520212
520212
Nope, your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
58 mins ago
Okay... I'm taking a look at it
– Tanmoy Krishna Das
58 mins ago
The problem was with the sort function. The default sort function sorts the values alphabetically. That's why you can't just use arr.sort(). I modified the code to reflect your needs.
– Tanmoy Krishna Das
50 mins ago
add a comment |
Nope, your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
58 mins ago
Okay... I'm taking a look at it
– Tanmoy Krishna Das
58 mins ago
The problem was with the sort function. The default sort function sorts the values alphabetically. That's why you can't just use arr.sort(). I modified the code to reflect your needs.
– Tanmoy Krishna Das
50 mins ago
Nope, your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
58 mins ago
Nope, your solution doesn't work when I pass this array: [5, 3, 2, 8, 1, 4, 11 ], it supposes to return [1, 3, 2, 8, 5, 4, 11], but it returns [1, 11, 2, 8, 3, 4, 5]
– progx
58 mins ago
Okay... I'm taking a look at it
– Tanmoy Krishna Das
58 mins ago
Okay... I'm taking a look at it
– Tanmoy Krishna Das
58 mins ago
The problem was with the sort function. The default sort function sorts the values alphabetically. That's why you can't just use arr.sort(). I modified the code to reflect your needs.
– Tanmoy Krishna Das
50 mins ago
The problem was with the sort function. The default sort function sorts the values alphabetically. That's why you can't just use arr.sort(). I modified the code to reflect your needs.
– Tanmoy Krishna Das
50 mins ago
add a comment |
Fun problem, thanks for sharing! I think this is a straightforward approach -
const compare = (a, b) =>
a < b ? -1
: a > b ? 1
: 0
const main = (arr) =>
{ const odds =
const idxs =
for (const [ i, x ] of arr.entries())
if (x & 1)
(odds.push(x), idxs.push(i))
// odds = [ 5, 3, 11, 1 ]
// idxs = [ 0, 1, 4, 6 ]
odds.sort(compare)
// no need to sort idxs, always inserted in order
// odds = [ 1, 3, 5, 11 ]
// idxs = [ 0, 1, 4, 6 ]
for (const [ i, x ] of odds.entries())
arr[idxs[i]] = x
return arr
}
console.log(main([ 5, 3, 2, 8, 11, 4, 1 ]))
// [ 1, 3, 2, 8, 5, 4, 11 ]
If you want main
to be an immutable operation, change the end to
const result = [ ...arr ]
for (const [ i, x ] of odds.entries())
result[idxs[i]] = x
return result
add a comment |
Fun problem, thanks for sharing! I think this is a straightforward approach -
const compare = (a, b) =>
a < b ? -1
: a > b ? 1
: 0
const main = (arr) =>
{ const odds =
const idxs =
for (const [ i, x ] of arr.entries())
if (x & 1)
(odds.push(x), idxs.push(i))
// odds = [ 5, 3, 11, 1 ]
// idxs = [ 0, 1, 4, 6 ]
odds.sort(compare)
// no need to sort idxs, always inserted in order
// odds = [ 1, 3, 5, 11 ]
// idxs = [ 0, 1, 4, 6 ]
for (const [ i, x ] of odds.entries())
arr[idxs[i]] = x
return arr
}
console.log(main([ 5, 3, 2, 8, 11, 4, 1 ]))
// [ 1, 3, 2, 8, 5, 4, 11 ]
If you want main
to be an immutable operation, change the end to
const result = [ ...arr ]
for (const [ i, x ] of odds.entries())
result[idxs[i]] = x
return result
add a comment |
Fun problem, thanks for sharing! I think this is a straightforward approach -
const compare = (a, b) =>
a < b ? -1
: a > b ? 1
: 0
const main = (arr) =>
{ const odds =
const idxs =
for (const [ i, x ] of arr.entries())
if (x & 1)
(odds.push(x), idxs.push(i))
// odds = [ 5, 3, 11, 1 ]
// idxs = [ 0, 1, 4, 6 ]
odds.sort(compare)
// no need to sort idxs, always inserted in order
// odds = [ 1, 3, 5, 11 ]
// idxs = [ 0, 1, 4, 6 ]
for (const [ i, x ] of odds.entries())
arr[idxs[i]] = x
return arr
}
console.log(main([ 5, 3, 2, 8, 11, 4, 1 ]))
// [ 1, 3, 2, 8, 5, 4, 11 ]
If you want main
to be an immutable operation, change the end to
const result = [ ...arr ]
for (const [ i, x ] of odds.entries())
result[idxs[i]] = x
return result
Fun problem, thanks for sharing! I think this is a straightforward approach -
const compare = (a, b) =>
a < b ? -1
: a > b ? 1
: 0
const main = (arr) =>
{ const odds =
const idxs =
for (const [ i, x ] of arr.entries())
if (x & 1)
(odds.push(x), idxs.push(i))
// odds = [ 5, 3, 11, 1 ]
// idxs = [ 0, 1, 4, 6 ]
odds.sort(compare)
// no need to sort idxs, always inserted in order
// odds = [ 1, 3, 5, 11 ]
// idxs = [ 0, 1, 4, 6 ]
for (const [ i, x ] of odds.entries())
arr[idxs[i]] = x
return arr
}
console.log(main([ 5, 3, 2, 8, 11, 4, 1 ]))
// [ 1, 3, 2, 8, 5, 4, 11 ]
If you want main
to be an immutable operation, change the end to
const result = [ ...arr ]
for (const [ i, x ] of odds.entries())
result[idxs[i]] = x
return result
const compare = (a, b) =>
a < b ? -1
: a > b ? 1
: 0
const main = (arr) =>
{ const odds =
const idxs =
for (const [ i, x ] of arr.entries())
if (x & 1)
(odds.push(x), idxs.push(i))
// odds = [ 5, 3, 11, 1 ]
// idxs = [ 0, 1, 4, 6 ]
odds.sort(compare)
// no need to sort idxs, always inserted in order
// odds = [ 1, 3, 5, 11 ]
// idxs = [ 0, 1, 4, 6 ]
for (const [ i, x ] of odds.entries())
arr[idxs[i]] = x
return arr
}
console.log(main([ 5, 3, 2, 8, 11, 4, 1 ]))
// [ 1, 3, 2, 8, 5, 4, 11 ]
const compare = (a, b) =>
a < b ? -1
: a > b ? 1
: 0
const main = (arr) =>
{ const odds =
const idxs =
for (const [ i, x ] of arr.entries())
if (x & 1)
(odds.push(x), idxs.push(i))
// odds = [ 5, 3, 11, 1 ]
// idxs = [ 0, 1, 4, 6 ]
odds.sort(compare)
// no need to sort idxs, always inserted in order
// odds = [ 1, 3, 5, 11 ]
// idxs = [ 0, 1, 4, 6 ]
for (const [ i, x ] of odds.entries())
arr[idxs[i]] = x
return arr
}
console.log(main([ 5, 3, 2, 8, 11, 4, 1 ]))
// [ 1, 3, 2, 8, 5, 4, 11 ]
edited 10 mins ago
answered 16 mins ago
user633183user633183
68.8k21137177
68.8k21137177
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54264468%2fhow-to-sort-elements-in-array-without-changing-other-elements-indexes%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown