Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

javascript - JS sort array of objets by specific string property (not ascending or descending)

do you know if there is a way to sort an array of objects using the sort() method for a specific property? In my case I'd like to sort my array first for "bananas", then for "pears", and then the rest.

const initialData = [
{ name: "strawberries", value: 12 },
{ name: "bananas", value: 3 },
{ name: "pears", value: 8 },
{ name: "pears", value: 7 },
{ name: "bananas", value: 10 },
{ name: "apples", value: 6 },
{ name: "bananas", value: 13 },
{ name: "bananas", value: 5 }
]

This is how I'd like the sorted data to look like:

const sortedData = [
{ name: "bananas", value: 3 },
{ name: "bananas", value: 10 },
{ name: "bananas", value: 13 },
{ name: "bananas", value: 5 },
{ name: "pears", value: 8 },
{ name: "pears", value: 7 },
{ name: "strawberries", value: 12 },
{ name: "apples", value: 6 }
]

I know that this function would sort my data ascending or descending:

initialData.sort(function(a, b) {
  if (a.name < b.name) {
    return -1;
  }
  if (a.name > b.name) {
    return 1;
  }
  return 0;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could take an object with the wanted order and take a large value as default for sorting.

const
    data = [{ name: "strawberries", value: 12 }, { name: "bananas", value: 3 }, { name: "pears", value: 8 }, { name: "pears", value: 7 }, { name: "bananas", value: 10 }, { name: "apples", value: 6 }, { name: "bananas", value: 13 }, { name: "bananas", value: 5 }],
    order = { bananas: 1, pears: 2 };

data.sort((a, b) => (order[a.name] || Number.MAX_VALUE) - (order[b.name] || Number.MAX_VALUE));

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...