I want to use an array of strings as template how to order other arrays.
var sort = ["this","is","my","custom","order"];
and then i want to sort an array of objects depending on a key (content) by that order:
var myObjects = [
{"id":1,"content":"is"},
{"id":2,"content":"my"},
{"id":3,"content":"this"},
{"id":4,"content":"custom"},
{"id":5,"content":"order"}
];
so that my result is:
sortedObject = [
{"id":3,"content":"this"},
{"id":1,"content":"is"},
{"id":2,"content":"my"},
{"id":4,"content":"custom"},
{"id":5,"content":"order"}
];
how would i do that?
You can do something like this with help of sort()
and indexOf()
var sort = ["this", "is", "my", "custom", "order"]; var myObjects = [{ "id": 1, "content": "is" }, { "id": 2, "content": "my" }, { "id": 3, "content": "this" }, { "id": 4, "content": "custom" }, { "id": 5, "content": "order" }]; var sortedObj = myObjects.sort(function(a, b) { return sort.indexOf(a.content) - sort.indexOf(b.content); }); document.write('<pre>' + JSON.stringify(sortedObj, null, 3) + '</pre>');
you need to use .map
var sort = ["this", "is", "my", "custom", "order"]; var myObjects = [{ "id": 1, "content": "is" }, { "id": 2, "content": "my" }, { "id": 3, "content": "this" }, { "id": 4, "content": "custom" }, { "id": 5, "content": "order" }]; var myObjectsSort = sort.map(function(e, i) { for (var i = 0; i < myObjects.length; ++i) { if (myObjects[i].content == e) return myObjects[i]; } }); document.write('<pre>' + JSON.stringify(myObjectsSort , null, 3) + '</pre>');
Create a new array and place the every object from
myObjects
consideringindex
of thesort
Try this:
var sort = ["this", "is", "my", "custom", "order"]; var myObjects = [{ "id": 1, "content": "is" }, { "id": 2, "content": "my" }, { "id": 3, "content": "this" }, { "id": 4, "content": "custom" }, { "id": 5, "content": "order" }]; var newArr = []; myObjects.forEach(function(item) { var index = sort.indexOf(item.content); newArr[index] = item; }); console.log(newArr);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
I suggest to use an object for the storing of the sort order.
var sort = ["this", "is", "my", "custom", "order"], sortObj = {}, myObjects = [{ "id": 1, "content": "is" }, { "id": 2, "content": "my" }, { "id": 3, "content": "this" }, { "id": 4, "content": "custom" }, { "id": 5, "content": "order" }]; sort.forEach(function (a, i) { sortObj[a] = i; }); myObjects.sort(function (a, b) { return sortObj[ a.content] - sortObj[ b.content]; }); document.write('<pre>' + JSON.stringify(myObjects, 0, 4) + '</pre>');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.