javascript - 提取每个数组中第一个 Index[0] 的内容如果我有一个数组并且其中有多个数组

标签 javascript arrays

如果我有一个数组,其中包含三个数组,并且想要提取每个数组中索引[1]的内容

Array(4) [Array(3), Array(3), Array(1), Array(1)]
length:4
[
0:Array(3) ["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"]  // Extract content of Index[0]
1:Array(3) ["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"]  // Extract content of Index[0]
2:Array(1) ["b32f4c08-8d53-5fed-8034-4bfb144dfe10"]  // Extract content of Index[0]
3:Array(1) ["b32f4c08-8d53-5fed-8034-4bfb144dfe10"]  // Extract content of Index[0]
]

在每一行中我只想提取第一个变量,这是我的结果:

let result = [
                ["cfdb9868-0f69-5781-b1e4-793301280788"],["cfdb9868-0f69-5781-b1e4-793301280788"],
                ["b32f4c08-8d53-5fed-8034-4bfb144dfe10"],["b32f4c08-8d53-5fed-8034-4bfb144dfe10"] 
             ]

我使用切片和分割只有第一个,但给我错误函数

最佳答案

非常简单的解决方案,使用 Array.prototype.map属性(property)

const input = [
  ["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"],
  ["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"],
  ["b32f4c08-8d53-5fed-8034-4bfb144dfe10"],
  ["b32f4c08-8d53-5fed-8034-4bfb144dfe10"]
]

const output = input.map(([firstElement])=>[firstElement])

console.log(output)

存储第 n 个变量有点复杂

const input = [
  ["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"],
  ["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"],
  ["b32f4c08-8d53-5fed-8034-4bfb144dfe10"],
  ["b32f4c08-8d53-5fed-8034-4bfb144dfe10"]
]

const output = (n) => input.map((element)=> element[n] ? [element[n]] : [])

console.log("0", JSON.stringify(output(0)))
console.log("1", JSON.stringify(output(1)))
console.log("2", JSON.stringify(output(2)))

假设如果不存在具有给定索引的元素,您可能不想保留空数组,您可以像这样修改上面的代码:

const input = [
  ["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"],
  ["cfdb9868-0f69-5781-b1e4-793301280788", "127.0.0.1", "9146"],
  ["b32f4c08-8d53-5fed-8034-4bfb144dfe10"],
  ["b32f4c08-8d53-5fed-8034-4bfb144dfe10"]
]

const output = (n) => input.reduce((list, element)=> element[n] ? [...list, element[n]] : list, [])

console.log("0", JSON.stringify(output(0)))
console.log("1", JSON.stringify(output(1)))
console.log("2", JSON.stringify(output(2)))

关于javascript - 提取每个数组中第一个 Index[0] 的内容如果我有一个数组并且其中有多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60321003/

相关文章:

javascript - 播放/暂停视频 onclick firefox

c - 如何使用 malloc 为结构体数组分配空间?

Javascript 将名称 array() 加一

javascript - 如何使用 js 或 jquery 将我的复选框数据放入 html 中的文本区域框?

javascript - 拆分多个数组 json 字符串

java - CompareTo 预期元素错误

javascript - 简化过滤js

javascript - 在 Indesign 中在脚注中插入字符

javascript - Vue.js 动态 href

javascript - 当字符从搜索栏中删除时,为什么我的 react 自动建议不起作用