过滤和排序对象数组

时间:2017-11-04 21:09:46

标签: javascript sorting

我有一个对象数组

// create a componentRef
const componentFactory = ComponentFactoryResolver.resolveComponentFactory(AngularComponent);
const componentRef = componentFactory.create(Injector);

// attach the componentRef to the angular ApplicationRef
ApplicationRef.attachView(componentRef.hostView);

// insert the root element of the new componentRef into any DOM node
const componentRoot: HTMLElement = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0];
const node = document.getElementById('insertionPoint'); 
Renderer2.insertBefore(node.parentNode, componentRoot, node);

// don't forget to destroy the component when you're done with it
ApplicationRef.detachView(componentRef.hostView);
componentRef.destroy();

我想选择并重新排序,以便将数组转换为

const a = [
  { name: 'z', items: [..] },
  { name: 'x', items: [..] },
  { name: 'y', items: [..] },
  { name: 'a', items: [..] },
]

即。我只想要名称为const a_new = [ { name: 'x', items: [..] }, { name: 'y', items: [..] }, { name: 'z', items: [..] }, ] xy的人,我希望按照某个特定顺序排序(不仅仅是字母数字)。

所以我想,例如,指定一个数组z,指出我将允许哪些名称以及如何对它们进行排序。

可能是

['x', 'y', 'z']

看起来有点内存沉重?

2 个答案:

答案 0 :(得分:1)

您可以使用以下方式构建地图:

const byName = new Map(a.map( obj => [obj.name, obj]));

所以现在我们可以轻松地将结果输入O(n):

 const result = ['x', 'y', 'z'].map(name => byName.get(name));

这应该比你的解决方案更快,但它的内存消耗要高得多。

答案 1 :(得分:0)

您可以先使用Array#filter过滤指定的元素,然后根据b(架构)数组中给定元素的索引对其进行排序。

&#13;
&#13;
const a = [
  { name: 'z', items: [] },
  { name: 'x', items: [] },
  { name: 'y', items: [] },
  { name: 'a', items: [] },
];

const b = ['x', 'y', 'z'];

const c = a.filter(({ name }) => b.includes(name))
           .sort(({ name: r }, { name: t }) => b.indexOf(r) - b.indexOf(t));
           
console.log(c);
&#13;
&#13;
&#13;

相关问题