How to sort elements in array without changing other elements indexes?












9















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.










share|improve this question





























    9















    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.










    share|improve this question



























      9












      9








      9








      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.










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 1 hour ago







      progx

















      asked 1 hour ago









      progxprogx

      309521




      309521
























          4 Answers
          4






          active

          oldest

          votes


















          4














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








          share|improve this answer


























          • 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
            51 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
            42 mins ago



















          3














          One option is to keep track of the indicies of the odd numbers in the original array, and after .reduceing 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 ]));








          share|improve this answer


























          • 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
            1 hour ago



















          0














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






          share|improve this answer


























          • 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
            1 hour ago











          • Okay... I'm taking a look at it

            – Tanmoy Krishna Das
            1 hour 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
            1 hour ago



















          0














          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





          share|improve this answer

























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


            }
            });














            draft saved

            draft discarded


















            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









            4














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








            share|improve this answer


























            • 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
              51 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
              42 mins ago
















            4














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








            share|improve this answer


























            • 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
              51 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
              42 mins ago














            4












            4








            4







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








            share|improve this answer















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






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 49 mins ago

























            answered 57 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
              51 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
              42 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
              51 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
              42 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
            51 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
            51 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
            42 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
            42 mins ago













            3














            One option is to keep track of the indicies of the odd numbers in the original array, and after .reduceing 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 ]));








            share|improve this answer


























            • 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
              1 hour ago
















            3














            One option is to keep track of the indicies of the odd numbers in the original array, and after .reduceing 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 ]));








            share|improve this answer


























            • 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
              1 hour ago














            3












            3








            3







            One option is to keep track of the indicies of the odd numbers in the original array, and after .reduceing 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 ]));








            share|improve this answer















            One option is to keep track of the indicies of the odd numbers in the original array, and after .reduceing 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 ]));






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 1 hour 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
              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
              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





            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
            1 hour ago





            Ah, the 11 was throwing things off, since .sort sorts lexiographically - use a custom .sort function instead, see edit

            – CertainPerformance
            1 hour ago











            0














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






            share|improve this answer


























            • 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
              1 hour ago











            • Okay... I'm taking a look at it

              – Tanmoy Krishna Das
              1 hour 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
              1 hour ago
















            0














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






            share|improve this answer


























            • 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
              1 hour ago











            • Okay... I'm taking a look at it

              – Tanmoy Krishna Das
              1 hour 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
              1 hour ago














            0












            0








            0







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






            share|improve this answer















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






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 1 hour 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
              1 hour ago











            • Okay... I'm taking a look at it

              – Tanmoy Krishna Das
              1 hour 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
              1 hour 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
              1 hour ago











            • Okay... I'm taking a look at it

              – Tanmoy Krishna Das
              1 hour 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
              1 hour 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
            1 hour 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
            1 hour ago













            Okay... I'm taking a look at it

            – Tanmoy Krishna Das
            1 hour ago





            Okay... I'm taking a look at it

            – Tanmoy Krishna Das
            1 hour 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
            1 hour 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
            1 hour ago











            0














            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





            share|improve this answer






























              0














              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





              share|improve this answer




























                0












                0








                0







                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





                share|improve this answer















                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 ]






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 28 mins ago

























                answered 35 mins ago









                user633183user633183

                68.8k21137177




                68.8k21137177






























                    draft saved

                    draft discarded




















































                    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.




                    draft saved


                    draft discarded














                    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





















































                    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







                    Popular posts from this blog

                    Сан-Квентин

                    8-я гвардейская общевойсковая армия

                    Алькесар