英文:
Pull values from array to a new single array
问题
以下是翻译好的内容:
我有一个这样的数组:
pa: [{
id: 1,
sa: [1, 2, 3]
}, {
id: 2,
sa: [1, 2, 3]
}, {
id: 3,
}]
其中一些对象包含一个 `sa` 数组,而另一些则没有。我想创建一个新数组,其中包含所有 `sa` 中的数字,放入一个新的单一数组中。
我尝试了以下方法,但它会添加多个数组:
for (let i = 0; i < pa.length; i++) {
if (pa[i].sa !== undefined && pa[i]?.sa) {
f.push(pa[i]?.sa?.map(a => a.id));
}
}
我希望最终的数组是:
newArray = [1, 2, 3, 1, 2, 3]
英文:
I have an array like this:
pa: [{
id: 1,
sa: [ 1, 2, 3 ]
}, {
id: 2,
sa: [ 1, 2, 3 ]
}, {
id: 3,
}]
Some of the objects contain an sa
array and some don't. I want to create a new array that contains all the numbers of sa
in a new single array
I have tried this but it will add in multiple arrays
for (let i = 0; i < pa.length; i++) {
if (pa[i].sa!== undefined && pa[i]?.sa) {
f.push(p[i]?.sa?.map(a=> a.id));
}
}
i want the final array to be
newArray = [1,2,3,1,2,3]
答案1
得分: 3
Sure, here is the translated code portion:
const
data = { pa: [{ id: 1, sa: [1, 2, 3] }, { id: 2, sa: [1, 2, 3] }, { id: 3 }] },
result = data.pa.flatMap(({ sa = [] }) => sa);
console.log(result);
Please let me know if you need any further assistance with this code.
英文:
You could take a flat mapping with a destructuring with optional array.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const
data = { pa: [{ id: 1, sa: [1, 2, 3] }, { id: 2, sa: [1, 2, 3] }, { id: 3 }] },
result = data.pa.flatMap(({ sa = [] }) => sa);
console.log(result);
<!-- end snippet -->
答案2
得分: 1
你可以通过将.flat()
应用于你的结果来获得一个单一的数组。
一个简化版本的你的代码:
const newArray = pa.map(e => e.sa ?? []).flat();
英文:
You can get a single array by just applying .flat()
to your result.
A simpler version of your code:
const newArray = pa.map(e => e.sa ?? []).flat();
答案3
得分: 1
以下是您要翻译的内容:
"有点讽刺的是,使用for循环的方法将比其他建议运行得更快,因为它不会创建数组的中间副本,并且在主观上与其他方法一样易读。
for (let i = 0, sa; i < pa.length; i++)
if (sa = pa[i].sa)
for (let j = 0; j < sa.length; j++)
newArray.push(sa[j]);"
英文:
Somewhat ironically, the approach with for loops will run a lot quicker than the other suggestions because it doesn't create intermediate copies of the array, and is subjectively just as readable.
for (let i = 0, sa; i < pa.length; i++)
if (sa = pa[i].sa)
for (let j = 0; j < sa.length; j++)
newArray.push(sa[j]);
答案4
得分: 0
let output = [];
let k = pa.map(item => {
if (item.sa) {
output = [...output, ...item.sa];
}
})
英文:
Not sharing an optimized answer as few answers are already their. Just using your approach correctly so that you know how your logic can be used.
let output = [];
let k = pa.map(item => {
if (item.sa) {
output = [...output, ...item.sa];
}
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论