如何有效地构建这个数组? [英] How to efficiently build this array?
问题描述
我有一个对象数组,例如:
I have an array of objects, e.g.:
[
{ a: 3, b: 2, c: 5, d: 6, e: 8 },
{ a: 1, b: 5, c: 3, d: 1, e: 2 }
]
现在我想将其转换为仅包含特定属性值但不包含对象本身的数组。例如,如果我对 a
, b
, c
和 d
,结果应如下所示:
Now I want to transform this to an array that contains only the values of specific properties, but without the objects themselves. E.g., if I am interested in a
, b
, c
, and d
, the result should look like this:
[ 3, 2, 5, 6, 1, 5, 3, 1 ]
我目前的做法看起来像这个:
My current approach looks like this:
const result = _.flatten(data.map(item => [ item.a, item.b, item.c, item.d ]));
是否有更好的(即更有效,甚至更可读)的方式来获得结果?
Is there a better (i.e., more efficient, and maybe even more readable) way to get the result?
推荐答案
你所拥有的东西对我来说似乎有很多可读性,并且很有效足够。但是你可以通过避免所有那些临时数组而不是循环两次来提高效率:
What you have seems plenty readable to me, and is likely efficient enough. But you can make it more efficient by avoiding all those temporary arrays and not looping twice:
const result = [];
data.forEach(item => result.push(item.a, item.b, item.c, item.d));
示例:
const data = [
{ a: 3, b: 2, c: 5, d: 6, e: 8 },
{ a: 1, b: 5, c: 3, d: 1, e: 2 }
];
const result = [];
data.forEach(item => result.push(item.a, item.b, item.c, item.d));
console.log(result);
有些引擎有效地推
真正,而其他引擎则没有那么多。如果效率是关键要求,您需要在目标环境中尝试将其与此进行比较:
Some engines do push
really efficiently, others not so much. If efficiency were a critical requirement, you'd want to experiment comparing that with this on your target environments:
const result = [];
let index = 0;
let n, l, item;
for (n = 0, l = data.length; n < l; ++n) {
item = data[n];
result[index++] = item.a;
result[index++] = item.b;
result[index++] = item.c;
result[index++] = item.d;
}
有三点需要注意:
- 直接推送到数组而不是使用
push
。 - 使用简单的
for
循环而不是forEach
。使用forEach
的绝对开销是如此之小,以至于从人的角度来看几乎不存在,但是它的相对开销很小循环非常大。 - 声明
i
,l
和item
在之外的
循环。如果我们在中为
声明它们,则会在每次循环迭代时重新创建它们,从而增加了开销。 (ES2015的语义为让
声明是强大而有用的,但在这种特殊情况下,我们不需要开销。)
- Pushing directly onto the array instead of using
push
. - Using a simple
for
loop instead offorEach
. The absolute overhead of usingforEach
is so small as to be virtually non-existant from a human perspective, but the relative overhead of it in a tight loop is quite large. - Declaring
i
,l
, anditem
outside thefor
loop. If we declared them within thefor
, they'd be recreated on each loop iteration, adding overhead. (ES2015's semantics forlet
declarations are powerful and useful, but in this particular case, we don't want the overhead.)
示例:
const data = [
{ a: 3, b: 2, c: 5, d: 6, e: 8 },
{ a: 1, b: 5, c: 3, d: 1, e: 2 }
];
const result = [];
let index = 0;
let n, l, item;
for (n = 0, l = data.length; n < l; ++n) {
item = data[n];
result[index++] = item.a;
result[index++] = item.b;
result[index++] = item.c;
result[index++] = item.d;
}
console.log(result);
这篇关于如何有效地构建这个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!