如何根据新数组更改旧数组的顺序



我有一个现有的数组,现在我想根据新数组的密钥更改旧数组的顺序

// Existing Array
var data = [
{
name: 'section-intro', 
children: ['service-addressBox', 'service-banner']
},
{name: 'section-breadcrumb', children: ['h', 'i', 'j']},
{name: 'section-products', children: []},
{name: 'section-about', children: []},
{name: 'section-timeline', children: []},
{name: 'section-nearbyOutlets', children: []}
]

// New Array
['section-nearbyOutlets', 'section-intro', 'section-products', 'section-breadcrumb', 'section-timeline', 'section-about']

如果两个数组具有相同数量的元素(或者如果您只对新数组中出现的元素感兴趣(,则可以使用map:尝试类似的操作

// Existing Array
const data = [
{
name: 'section-intro',
children: ['service-addressBox', 'service-banner']
},
{ name: 'section-breadcrumb', children: ['h', 'i', 'j'] },
{ name: 'section-products', children: [] },
{ name: 'section-about', children: [] },
{ name: 'section-timeline', children: [] },
{ name: 'section-nearbyOutlets', children: [] }
]
// New Array
const newArray = ['section-nearbyOutlets', 'section-intro', 'section-products', 'section-breadcrumb', 'section-timeline', 'section-about']
const orderedArray = newArray.map(element => data.find(originalElement => originalElement.name === element))
console.log(JSON.stringify(orderedArray, null, 2))

在这里,我们创建了一个新的数组(orderedArray(,但如果您愿意,也可以覆盖现有的两个数组中的一个。

您可以通过按名称手动排序来完成

var temp=[]
for(let name :newarray){
for(let datum:data){
if(datum.name==name)
temp.append(datum)
}
}
data=temp

如果我们谈论的是订购,那么您可以使用Array.sort

// Existing Array
let data = [
{
name: 'section-intro', 
children: ['service-addressBox', 'service-banner']
},
{name: 'section-breadcrumb', children: ['h', 'i', 'j']},
{name: 'section-products', children: []},
{name: 'section-about', children: []},
{name: 'section-timeline', children: []},
{name: 'section-nearbyOutlets', children: []}
]
// New Array
const order = ['section-nearbyOutlets', 'section-intro',
'section-products', 'section-breadcrumb', 'section-timeline', 'section-about']
data = data.sort((a, b) => {
const ixa = order.indexOf(a.name)
const ixb = order.indexOf(b.name)
return ixa < ixb ? -1 : 1
})
console.log(data)

最新更新