sort array of objects if the object has a property












1















I have an object like this:



"data": [
{
"name": "name1",
"price": 4.2,
},
{
"name": "name2",
"price": 12.9,
"newOne": {}
},
{
"name": "name3",
"price": 10.9,
"newOne": {
"code": "02ec583021de8e36ae8006c3caef72d9",
"name": "מבצע 13"
}
},
{
"name": "name3",
"price": 10.9,
},
],


I have tried many ways to sort it...Need some help



If this array has a "newOne" property I Want that object to be first in the array etc'...



If you have 3 objects with the proprty "newOne" so they will be the first to show one after the other and not that the next mapping object will be at the top of the array.



I am using React if that means anything



Thanks!










share|improve this question



























    1















    I have an object like this:



    "data": [
    {
    "name": "name1",
    "price": 4.2,
    },
    {
    "name": "name2",
    "price": 12.9,
    "newOne": {}
    },
    {
    "name": "name3",
    "price": 10.9,
    "newOne": {
    "code": "02ec583021de8e36ae8006c3caef72d9",
    "name": "מבצע 13"
    }
    },
    {
    "name": "name3",
    "price": 10.9,
    },
    ],


    I have tried many ways to sort it...Need some help



    If this array has a "newOne" property I Want that object to be first in the array etc'...



    If you have 3 objects with the proprty "newOne" so they will be the first to show one after the other and not that the next mapping object will be at the top of the array.



    I am using React if that means anything



    Thanks!










    share|improve this question

























      1












      1








      1








      I have an object like this:



      "data": [
      {
      "name": "name1",
      "price": 4.2,
      },
      {
      "name": "name2",
      "price": 12.9,
      "newOne": {}
      },
      {
      "name": "name3",
      "price": 10.9,
      "newOne": {
      "code": "02ec583021de8e36ae8006c3caef72d9",
      "name": "מבצע 13"
      }
      },
      {
      "name": "name3",
      "price": 10.9,
      },
      ],


      I have tried many ways to sort it...Need some help



      If this array has a "newOne" property I Want that object to be first in the array etc'...



      If you have 3 objects with the proprty "newOne" so they will be the first to show one after the other and not that the next mapping object will be at the top of the array.



      I am using React if that means anything



      Thanks!










      share|improve this question














      I have an object like this:



      "data": [
      {
      "name": "name1",
      "price": 4.2,
      },
      {
      "name": "name2",
      "price": 12.9,
      "newOne": {}
      },
      {
      "name": "name3",
      "price": 10.9,
      "newOne": {
      "code": "02ec583021de8e36ae8006c3caef72d9",
      "name": "מבצע 13"
      }
      },
      {
      "name": "name3",
      "price": 10.9,
      },
      ],


      I have tried many ways to sort it...Need some help



      If this array has a "newOne" property I Want that object to be first in the array etc'...



      If you have 3 objects with the proprty "newOne" so they will be the first to show one after the other and not that the next mapping object will be at the top of the array.



      I am using React if that means anything



      Thanks!







      javascript arrays json reactjs sorting






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 19 '18 at 14:50









      user1102152user1102152

      3117




      3117
























          4 Answers
          4






          active

          oldest

          votes


















          5














          You could check for the property and take the check for the delta for sorting.






          var data = [{ name: "name1", price: 4.2 }, { name: "name2", price: 12.9, newOne: {} }, { name: "name3", price: 10.9, newOne: { code: "02ec583021de8e36ae8006c3caef72d9", name: "מבצע 13" } }, { name: "name3", price: 10.9 }];

          data.sort((a, b) => ('newOne' in b) - ('newOne' in a));

          console.log(data);

          .as-console-wrapper { max-height: 100% !important; top: 0; }








          share|improve this answer



















          • 1





            TIL maths on booleans will implicitly coerce them to ints. Thank you! :-D

            – dgeare
            Nov 19 '18 at 14:59



















          0














          You can use the function unshift from array to achieve your goal.




          The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.







          const data = 
          [
          {
          "name": "name1",
          "price": 4.2,
          },
          {
          "name": "name2",
          "price": 12.9,
          "newOne": {}
          },
          {
          "name": "name3",
          "price": 10.9,
          "newOne": {
          "code": "02ec583021de8e36ae8006c3caef72d9",
          "name": "מבצע 13"
          }
          },
          {
          "name": "name3",
          "price": 10.9,
          },
          ]

          let result =
          data.forEach(item => {
          if (item.newOne) result.unshift(item)
          else result.push(item)
          })

          console.log(result)





          Same could be achieved with reduce:



          const result = data.reduce((agg, itr) => {
          if (itr.newOne) agg.unshift(itr)
          else agg.push(itr)
          return agg
          }, )

          console.log(result)





          share|improve this answer































            0














            This should be doable by treating items with a set newOne property as greater in value than those that don't.






            var t = {"data": [
            {
            "name": "name1",
            "price": 4.2,
            },
            {
            "name": "name2",
            "price": 12.9,
            "newOne": {}
            },
            {
            "name": "name3",
            "price": 10.9,
            "newOne": {
            "code": "02ec583021de8e36ae8006c3caef72d9",
            "name": "מבצע 13"
            }
            },
            {
            "name": "name3",
            "price": 10.9,
            },
            ]};

            t.data.sort(function(a,b){
            var aVal = a.newOne == undefined ? 0 : 1;
            var bVal = b.newOne == undefined ? 0 : 1;
            return bVal - aVal;
            });

            console.log(t.data);








            share|improve this answer































              0














              Here is another sorting function without using array in:



              data.sort((a,b) => a.newOne === b.newOne ? 0 : a.newOne ? -1 : 1)





              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%2f53377136%2fsort-array-of-objects-if-the-object-has-a-property%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









                5














                You could check for the property and take the check for the delta for sorting.






                var data = [{ name: "name1", price: 4.2 }, { name: "name2", price: 12.9, newOne: {} }, { name: "name3", price: 10.9, newOne: { code: "02ec583021de8e36ae8006c3caef72d9", name: "מבצע 13" } }, { name: "name3", price: 10.9 }];

                data.sort((a, b) => ('newOne' in b) - ('newOne' in a));

                console.log(data);

                .as-console-wrapper { max-height: 100% !important; top: 0; }








                share|improve this answer



















                • 1





                  TIL maths on booleans will implicitly coerce them to ints. Thank you! :-D

                  – dgeare
                  Nov 19 '18 at 14:59
















                5














                You could check for the property and take the check for the delta for sorting.






                var data = [{ name: "name1", price: 4.2 }, { name: "name2", price: 12.9, newOne: {} }, { name: "name3", price: 10.9, newOne: { code: "02ec583021de8e36ae8006c3caef72d9", name: "מבצע 13" } }, { name: "name3", price: 10.9 }];

                data.sort((a, b) => ('newOne' in b) - ('newOne' in a));

                console.log(data);

                .as-console-wrapper { max-height: 100% !important; top: 0; }








                share|improve this answer



















                • 1





                  TIL maths on booleans will implicitly coerce them to ints. Thank you! :-D

                  – dgeare
                  Nov 19 '18 at 14:59














                5












                5








                5







                You could check for the property and take the check for the delta for sorting.






                var data = [{ name: "name1", price: 4.2 }, { name: "name2", price: 12.9, newOne: {} }, { name: "name3", price: 10.9, newOne: { code: "02ec583021de8e36ae8006c3caef72d9", name: "מבצע 13" } }, { name: "name3", price: 10.9 }];

                data.sort((a, b) => ('newOne' in b) - ('newOne' in a));

                console.log(data);

                .as-console-wrapper { max-height: 100% !important; top: 0; }








                share|improve this answer













                You could check for the property and take the check for the delta for sorting.






                var data = [{ name: "name1", price: 4.2 }, { name: "name2", price: 12.9, newOne: {} }, { name: "name3", price: 10.9, newOne: { code: "02ec583021de8e36ae8006c3caef72d9", name: "מבצע 13" } }, { name: "name3", price: 10.9 }];

                data.sort((a, b) => ('newOne' in b) - ('newOne' in a));

                console.log(data);

                .as-console-wrapper { max-height: 100% !important; top: 0; }








                var data = [{ name: "name1", price: 4.2 }, { name: "name2", price: 12.9, newOne: {} }, { name: "name3", price: 10.9, newOne: { code: "02ec583021de8e36ae8006c3caef72d9", name: "מבצע 13" } }, { name: "name3", price: 10.9 }];

                data.sort((a, b) => ('newOne' in b) - ('newOne' in a));

                console.log(data);

                .as-console-wrapper { max-height: 100% !important; top: 0; }





                var data = [{ name: "name1", price: 4.2 }, { name: "name2", price: 12.9, newOne: {} }, { name: "name3", price: 10.9, newOne: { code: "02ec583021de8e36ae8006c3caef72d9", name: "מבצע 13" } }, { name: "name3", price: 10.9 }];

                data.sort((a, b) => ('newOne' in b) - ('newOne' in a));

                console.log(data);

                .as-console-wrapper { max-height: 100% !important; top: 0; }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 19 '18 at 14:53









                Nina ScholzNina Scholz

                185k1596168




                185k1596168








                • 1





                  TIL maths on booleans will implicitly coerce them to ints. Thank you! :-D

                  – dgeare
                  Nov 19 '18 at 14:59














                • 1





                  TIL maths on booleans will implicitly coerce them to ints. Thank you! :-D

                  – dgeare
                  Nov 19 '18 at 14:59








                1




                1





                TIL maths on booleans will implicitly coerce them to ints. Thank you! :-D

                – dgeare
                Nov 19 '18 at 14:59





                TIL maths on booleans will implicitly coerce them to ints. Thank you! :-D

                – dgeare
                Nov 19 '18 at 14:59













                0














                You can use the function unshift from array to achieve your goal.




                The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.







                const data = 
                [
                {
                "name": "name1",
                "price": 4.2,
                },
                {
                "name": "name2",
                "price": 12.9,
                "newOne": {}
                },
                {
                "name": "name3",
                "price": 10.9,
                "newOne": {
                "code": "02ec583021de8e36ae8006c3caef72d9",
                "name": "מבצע 13"
                }
                },
                {
                "name": "name3",
                "price": 10.9,
                },
                ]

                let result =
                data.forEach(item => {
                if (item.newOne) result.unshift(item)
                else result.push(item)
                })

                console.log(result)





                Same could be achieved with reduce:



                const result = data.reduce((agg, itr) => {
                if (itr.newOne) agg.unshift(itr)
                else agg.push(itr)
                return agg
                }, )

                console.log(result)





                share|improve this answer




























                  0














                  You can use the function unshift from array to achieve your goal.




                  The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.







                  const data = 
                  [
                  {
                  "name": "name1",
                  "price": 4.2,
                  },
                  {
                  "name": "name2",
                  "price": 12.9,
                  "newOne": {}
                  },
                  {
                  "name": "name3",
                  "price": 10.9,
                  "newOne": {
                  "code": "02ec583021de8e36ae8006c3caef72d9",
                  "name": "מבצע 13"
                  }
                  },
                  {
                  "name": "name3",
                  "price": 10.9,
                  },
                  ]

                  let result =
                  data.forEach(item => {
                  if (item.newOne) result.unshift(item)
                  else result.push(item)
                  })

                  console.log(result)





                  Same could be achieved with reduce:



                  const result = data.reduce((agg, itr) => {
                  if (itr.newOne) agg.unshift(itr)
                  else agg.push(itr)
                  return agg
                  }, )

                  console.log(result)





                  share|improve this answer


























                    0












                    0








                    0







                    You can use the function unshift from array to achieve your goal.




                    The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.







                    const data = 
                    [
                    {
                    "name": "name1",
                    "price": 4.2,
                    },
                    {
                    "name": "name2",
                    "price": 12.9,
                    "newOne": {}
                    },
                    {
                    "name": "name3",
                    "price": 10.9,
                    "newOne": {
                    "code": "02ec583021de8e36ae8006c3caef72d9",
                    "name": "מבצע 13"
                    }
                    },
                    {
                    "name": "name3",
                    "price": 10.9,
                    },
                    ]

                    let result =
                    data.forEach(item => {
                    if (item.newOne) result.unshift(item)
                    else result.push(item)
                    })

                    console.log(result)





                    Same could be achieved with reduce:



                    const result = data.reduce((agg, itr) => {
                    if (itr.newOne) agg.unshift(itr)
                    else agg.push(itr)
                    return agg
                    }, )

                    console.log(result)





                    share|improve this answer













                    You can use the function unshift from array to achieve your goal.




                    The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.







                    const data = 
                    [
                    {
                    "name": "name1",
                    "price": 4.2,
                    },
                    {
                    "name": "name2",
                    "price": 12.9,
                    "newOne": {}
                    },
                    {
                    "name": "name3",
                    "price": 10.9,
                    "newOne": {
                    "code": "02ec583021de8e36ae8006c3caef72d9",
                    "name": "מבצע 13"
                    }
                    },
                    {
                    "name": "name3",
                    "price": 10.9,
                    },
                    ]

                    let result =
                    data.forEach(item => {
                    if (item.newOne) result.unshift(item)
                    else result.push(item)
                    })

                    console.log(result)





                    Same could be achieved with reduce:



                    const result = data.reduce((agg, itr) => {
                    if (itr.newOne) agg.unshift(itr)
                    else agg.push(itr)
                    return agg
                    }, )

                    console.log(result)





                    const data = 
                    [
                    {
                    "name": "name1",
                    "price": 4.2,
                    },
                    {
                    "name": "name2",
                    "price": 12.9,
                    "newOne": {}
                    },
                    {
                    "name": "name3",
                    "price": 10.9,
                    "newOne": {
                    "code": "02ec583021de8e36ae8006c3caef72d9",
                    "name": "מבצע 13"
                    }
                    },
                    {
                    "name": "name3",
                    "price": 10.9,
                    },
                    ]

                    let result =
                    data.forEach(item => {
                    if (item.newOne) result.unshift(item)
                    else result.push(item)
                    })

                    console.log(result)





                    const data = 
                    [
                    {
                    "name": "name1",
                    "price": 4.2,
                    },
                    {
                    "name": "name2",
                    "price": 12.9,
                    "newOne": {}
                    },
                    {
                    "name": "name3",
                    "price": 10.9,
                    "newOne": {
                    "code": "02ec583021de8e36ae8006c3caef72d9",
                    "name": "מבצע 13"
                    }
                    },
                    {
                    "name": "name3",
                    "price": 10.9,
                    },
                    ]

                    let result =
                    data.forEach(item => {
                    if (item.newOne) result.unshift(item)
                    else result.push(item)
                    })

                    console.log(result)






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 19 '18 at 14:56









                    omri_saadonomri_saadon

                    7,03041444




                    7,03041444























                        0














                        This should be doable by treating items with a set newOne property as greater in value than those that don't.






                        var t = {"data": [
                        {
                        "name": "name1",
                        "price": 4.2,
                        },
                        {
                        "name": "name2",
                        "price": 12.9,
                        "newOne": {}
                        },
                        {
                        "name": "name3",
                        "price": 10.9,
                        "newOne": {
                        "code": "02ec583021de8e36ae8006c3caef72d9",
                        "name": "מבצע 13"
                        }
                        },
                        {
                        "name": "name3",
                        "price": 10.9,
                        },
                        ]};

                        t.data.sort(function(a,b){
                        var aVal = a.newOne == undefined ? 0 : 1;
                        var bVal = b.newOne == undefined ? 0 : 1;
                        return bVal - aVal;
                        });

                        console.log(t.data);








                        share|improve this answer




























                          0














                          This should be doable by treating items with a set newOne property as greater in value than those that don't.






                          var t = {"data": [
                          {
                          "name": "name1",
                          "price": 4.2,
                          },
                          {
                          "name": "name2",
                          "price": 12.9,
                          "newOne": {}
                          },
                          {
                          "name": "name3",
                          "price": 10.9,
                          "newOne": {
                          "code": "02ec583021de8e36ae8006c3caef72d9",
                          "name": "מבצע 13"
                          }
                          },
                          {
                          "name": "name3",
                          "price": 10.9,
                          },
                          ]};

                          t.data.sort(function(a,b){
                          var aVal = a.newOne == undefined ? 0 : 1;
                          var bVal = b.newOne == undefined ? 0 : 1;
                          return bVal - aVal;
                          });

                          console.log(t.data);








                          share|improve this answer


























                            0












                            0








                            0







                            This should be doable by treating items with a set newOne property as greater in value than those that don't.






                            var t = {"data": [
                            {
                            "name": "name1",
                            "price": 4.2,
                            },
                            {
                            "name": "name2",
                            "price": 12.9,
                            "newOne": {}
                            },
                            {
                            "name": "name3",
                            "price": 10.9,
                            "newOne": {
                            "code": "02ec583021de8e36ae8006c3caef72d9",
                            "name": "מבצע 13"
                            }
                            },
                            {
                            "name": "name3",
                            "price": 10.9,
                            },
                            ]};

                            t.data.sort(function(a,b){
                            var aVal = a.newOne == undefined ? 0 : 1;
                            var bVal = b.newOne == undefined ? 0 : 1;
                            return bVal - aVal;
                            });

                            console.log(t.data);








                            share|improve this answer













                            This should be doable by treating items with a set newOne property as greater in value than those that don't.






                            var t = {"data": [
                            {
                            "name": "name1",
                            "price": 4.2,
                            },
                            {
                            "name": "name2",
                            "price": 12.9,
                            "newOne": {}
                            },
                            {
                            "name": "name3",
                            "price": 10.9,
                            "newOne": {
                            "code": "02ec583021de8e36ae8006c3caef72d9",
                            "name": "מבצע 13"
                            }
                            },
                            {
                            "name": "name3",
                            "price": 10.9,
                            },
                            ]};

                            t.data.sort(function(a,b){
                            var aVal = a.newOne == undefined ? 0 : 1;
                            var bVal = b.newOne == undefined ? 0 : 1;
                            return bVal - aVal;
                            });

                            console.log(t.data);








                            var t = {"data": [
                            {
                            "name": "name1",
                            "price": 4.2,
                            },
                            {
                            "name": "name2",
                            "price": 12.9,
                            "newOne": {}
                            },
                            {
                            "name": "name3",
                            "price": 10.9,
                            "newOne": {
                            "code": "02ec583021de8e36ae8006c3caef72d9",
                            "name": "מבצע 13"
                            }
                            },
                            {
                            "name": "name3",
                            "price": 10.9,
                            },
                            ]};

                            t.data.sort(function(a,b){
                            var aVal = a.newOne == undefined ? 0 : 1;
                            var bVal = b.newOne == undefined ? 0 : 1;
                            return bVal - aVal;
                            });

                            console.log(t.data);





                            var t = {"data": [
                            {
                            "name": "name1",
                            "price": 4.2,
                            },
                            {
                            "name": "name2",
                            "price": 12.9,
                            "newOne": {}
                            },
                            {
                            "name": "name3",
                            "price": 10.9,
                            "newOne": {
                            "code": "02ec583021de8e36ae8006c3caef72d9",
                            "name": "מבצע 13"
                            }
                            },
                            {
                            "name": "name3",
                            "price": 10.9,
                            },
                            ]};

                            t.data.sort(function(a,b){
                            var aVal = a.newOne == undefined ? 0 : 1;
                            var bVal = b.newOne == undefined ? 0 : 1;
                            return bVal - aVal;
                            });

                            console.log(t.data);






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 19 '18 at 14:58









                            dgearedgeare

                            2,05731422




                            2,05731422























                                0














                                Here is another sorting function without using array in:



                                data.sort((a,b) => a.newOne === b.newOne ? 0 : a.newOne ? -1 : 1)





                                share|improve this answer




























                                  0














                                  Here is another sorting function without using array in:



                                  data.sort((a,b) => a.newOne === b.newOne ? 0 : a.newOne ? -1 : 1)





                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    Here is another sorting function without using array in:



                                    data.sort((a,b) => a.newOne === b.newOne ? 0 : a.newOne ? -1 : 1)





                                    share|improve this answer













                                    Here is another sorting function without using array in:



                                    data.sort((a,b) => a.newOne === b.newOne ? 0 : a.newOne ? -1 : 1)






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 19 '18 at 15:00









                                    Goran.itGoran.it

                                    3,38511621




                                    3,38511621






























                                        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%2f53377136%2fsort-array-of-objects-if-the-object-has-a-property%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







                                        這個網誌中的熱門文章

                                        Tangent Lines Diagram Along Smooth Curve

                                        Yusuf al-Mu'taman ibn Hud

                                        Zucchini