1

I'm trying to sort the next array alphabetically by the data keys:

array = [
{index: 1,
 data: "d"
},
{index: 2,
 data: "c"
},
{index: 3,
 data: "a"
},
{index: 4,
 data: "f"
},
{index: 5,
 data: "e"
},
{index: 6,
 data: "b"
}
];

such that it will become as follows:

array = [
{index: 3,
 data: "a"
},
{index: 6,
 data: "b"
},
{index: 2,
 data: "c"
},
{index: 1,
 data: "d"
},
{index: 5,
 data: "e"
},
{index: 4,
 data: "f"
}
];

Already found and tried something like this:

array.sort(function (a, b) { return a[1] - b[1]; });

but with no success. Is there a simple way to achieve this? Pure js please.

Bob Vandevliet
  • 213
  • 3
  • 14

2 Answers2

1

You need to access by key not by index

let array = [{index: 1, data: "d"},{index: 2, data: "c"},{index: 3, data: "a"},{index: 4, data: "f"},{index: 5, data: "e"},{index: 6, data: "b"}];

array.sort( (f, s) => f.data.localeCompare(s.data) );

console.log(array);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

You could sort by property data with String#localeCompare

var array = [{ index: 1, data: "d" }, { index: 2, data: "c" }, { index: 3, data: "a" }, { index: 4, data: "f" }, { index: 5, data: "e" }, { index: 6, data: "b" }];

array.sort(function (a, b) { return a.data.localeCompare(b.data); });
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392