基于任意排序的Javascript数组排序

基于任意排序的Javascript数组排序,javascript,arrays,sorting,Javascript,Arrays,Sorting,假设我有一个基于三种语言需要任意订购的书籍列表。该书的语言由字符串表示。在包含多种语言的书籍中,它是一个逗号分隔的语言字符串,其中英语总是排在西班牙语和法语之前,西班牙语总是排在法语之前 [ { language: 'English' }, { language: 'French' }, { language: 'English, French' }, { language: 'Spanish, French' }, { language: 'English, Spanish, French'

假设我有一个基于三种语言需要任意订购的书籍列表。该书的语言由字符串表示。在包含多种语言的书籍中,它是一个逗号分隔的语言字符串,其中英语总是排在西班牙语和法语之前,西班牙语总是排在法语之前

[
{ language: 'English' },
{ language: 'French' },
{ language: 'English, French' },
{ language: 'Spanish, French' },
{ language: 'English, Spanish, French' }
{ language: 'Spanish' }
]
如果我想对这个数组进行排序,使英语的书总是排在第一位,然后是西班牙语的书,然后是法语的书,除了生成一个包含正确顺序的数组(如下面所示)之外,还有其他方法吗

const orderArray = ['English', 'English, Spanish', 'English, Spanish, French', 'English, French', 'Spanish, French', 'Spanish', 'French']
然后用这样的东西在上面循环

const orderBooks = (books) => {
    const orderedBooks = [];
        orderArray.forEach((language) => {
            const bookIndex = books.findIndex(book => book.language === language);
            if (bookIndex >= 0) {
                orderedBooks.push(books[bookIndex]);
            }
        
    });
    return orderedBooks;
};
['English', 'Spanish', 'French']
有没有一种方法可以根据类似这样的简单偏好数组对它们进行排序

const orderBooks = (books) => {
    const orderedBooks = [];
        orderArray.forEach((language) => {
            const bookIndex = books.findIndex(book => book.language === language);
            if (bookIndex >= 0) {
                orderedBooks.push(books[bookIndex]);
            }
        
    });
    return orderedBooks;
};
['English', 'Spanish', 'French']

你可以根据一本书中的第一种语言而不是另一本书中的第一种语言进行排序

  books.sort((a, b) => {
     const difference = orderArray.find(language =>  
       a.includes(language) !== b.includes(language)
     );
     return a.includes(difference) - b.includes(difference);
 });
更复杂(/优雅)的实现是:

 const sortBy = (comp, ...others) => (a, b) =>
   a.includes(comp) - b.includes(comp) || sortBy(...others)(a, b);

 books.sort(sortBy(...preferenceArray));
“有没有办法……”当然。拆分语言并比较
preferenceArray.indexOf(语言)