-1

I have a JSON, which I successfully can sort numerical.

data["example"].sort(function (a, b) {
return a["one"] - b["two"];
});

// Output:
0: {location: "0"}
1: {location: "0"}
2: {location: "0"}
3: {location: "0"}
4: {location: "0"}
5: {location: "0"}
6: {location: "0"}
7: {location: "0"}
8: {location: "1"}
9: {location: "2"}
10: {location: "3"}
11: {location: "4"}
12: {location: "5"}
13: {location: "6"}
14: {location: "7"}

However, I want it to sort starting from 1 to , and after that, append all the 0's.

Like this:

0: {location: "1"}
1: {location: "2"}
2: {location: "3"}
3: {location: "4"}
4: {location: "5"}
5: {location: "6"}
6: {location: "7"}
7: {location: "0"}
8: {location: "0"}
9: {location: "0"}
10: {location: "0"}
11: {location: "0"}
12: {location: "0"}
13: {location: "0"}
14: {location: "0"}

I am sure, there is an easy solution to this, but I can't find anything about that specific numerical sort.

rojadesign
  • 385
  • 3
  • 14
  • 2
    Possible duplicate of [Using Javascript .sort() on an array to put all the zeros at the end](https://stackoverflow.com/questions/26006062/using-javascript-sort-on-an-array-to-put-all-the-zeros-at-the-end), or [Sort an array of objects in ascending order but put all zeros at the end](https://stackoverflow.com/q/50933086/215552) – Heretic Monkey Oct 23 '18 at 14:09
  • 1
    There is absolutely no JSON in this query. [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – str Oct 23 '18 at 14:11

2 Answers2

2

You can check if location is 0, if it is, use Infinity to sort to make sure all location will be placed in the end of the array.

let arr = [{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"1"},{"location":"2"},{"location":"3"},{"location":"4"},{"location":"5"},{"location":"6"},{"location":"7"}];

arr.sort(function(a, b) {
  return (a.location === "0" ? Infinity : a.location) - (b.location === "0" ? Infinity : b.location);
});

console.log(arr);

// Output:
// [{"location":"1"},{"location":"2"},{"location":"3"},{"location":"4"},{"location":"5"},{"location":"6"},{"location":"7"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"}];
rojadesign
  • 385
  • 3
  • 14
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

after get output run for

 for (let i = 0; i < array.length; i++) {
             array[i].location = i+1;

  }

or use map like

let counter = 1;
data["example"].sort(function (a, b) {
return a["one"] - b["two"];
}).map(c=> {c.location = counter++;return c});
hossein sedighian
  • 1,711
  • 1
  • 13
  • 16