[英]How can I sort an array by another array of objects?
如何按字符串对数组进行排序?
const filter = [
{ index: "First" },
{ index: "Second" },
{ index: "Third" }
]
const data = [
{ title: 'Apple', index: "Second" },
{ title: 'Samsung', index: "First" },
{ title: 'BMW', index: "Third" },
{ title: 'Apple', index: "Second" },
{ title: 'Apple', index: "Second" },
{ title: 'Samsung', index: "First" }
]
预期成绩:
const data = [
{ title: 'Samsung', index: "First" },
{ title: 'Samsung', index: "First" },
{ title: 'Apple', index: "Second" },
{ title: 'Apple', index: "Second" },
{ title: 'BMW', index: "Third" }
]
如何正确迭代两个数组? 我是否必须遍历两个数组才能做到这一点? 还是有另一种方法可以获得所需的结果?
给定三个输入——“第一”、“第二”、“第三”,是否会有更多这些索引?
Array#reduce
,迭代filter
并将每个对象的index
属性及其在数组中的index
保存在Map
Array#sort
,根据上图中的index
属性值对data
进行排序 const filter = [ { index: "First" }, { index: "Second" }, { index: "Third" } ], data = [ { title: 'Apple', index: "Second" }, { title: 'Samsung', index: "First" }, { title: 'BMW', index: "Third" }, { title: 'Apple', index: "Second" }, { title: 'Apple', index: "Second" }, { title: 'Samsung', index: "First" } ]; const indexSortMap = filter.reduce((map, { index }, i) => map.set(index, i), new Map); data.sort(({ index: a }, { index: b }) => indexSortMap.get(a) - indexSortMap.get(b)); console.log(data);
将Array#sort
与自定义 compareFunction 和Array#findIndex
与自定义回调函数一起使用
const filter = [ { index: "First",}, {index: "Second",}, {index: "Third",}]; const data = [ { title: 'Apple', index: "Second" }, { title: 'Samsung', index: "First" }, { title: 'BMW', index: "Third" }, { title: 'Apple', index: "Second" }, { title: 'Apple', index: "Second" }, { title: 'Samsung', index: "First" } ]; data.sort((a ,b) => { return filter.findIndex(i => i.index === a.index) - filter.findIndex(i => i.index === b.index); }); console.log(data);
一种可能的解决方案(并且很简单)是迭代这两个数组。 它们将根据“过滤器”数组的顺序推送:
const sortedArray = []
filter.forEach(fil=> {
data.forEach(dat=>{
if(dat.index===fil.index)
sortedArray.push(dat)
})
})
console.log(sortedArray)
一种方法是将对象推送到三个不同的数组,每个数组用于一个索引,然后连接数组。
var arr1 = [],arr2 = [],arr3 = [], data = [ { title: 'Apple', index: "Second" }, { title: 'Samsung', index: "First" }, { title: 'BMW', index: "Third" }, { title: 'Apple', index: "Second" }, { title: 'Apple', index: "Second" }, { title: 'Samsung', index: "First" } ]; for(d of data) d.index == 'First' ? arr1.push(d) : d.index == 'Second' ? arr2.push(d) : arr3.push(d); data = [].concat.apply([], [arr1, arr2, arr3]); console.log(data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.