【问题标题】:Find zero index data in 2d Array Javascript在 2d Array Javascript 中查找零索引数据
【发布时间】:2019-03-10 11:50:02
【问题描述】:

获取二维数组javascript中的所有0索引数据

let a = [["", "2", "", ""], ["1", "3", "", ""], ["", "", "4", ""]]
index = 0

output = ["", "1", ""]

同样获取所有剩余的索引数据

index= 1
output = ["2", "3", ""]

【问题讨论】:

    标签: javascript multidimensional-array ecmascript-6 underscore.js lodash


    【解决方案1】:

    您可以将Array#map 方法与ES6 destructuring feature 一起使用。解构有助于从对象中提取某些属性(Javascript Array 也是一个对象)。

    let a = [
      ["", "2", "", ""],
      ["1", "3", "", ""],
      ["", "", "4", ""]
    ];
    let index = 0;
    
    let output = a.map(({[ index ]: v }) => v)
    
    console.log(output);
    
    
    index = 1;
    
    output = a.map(({[ index ]: v }) => v)
    
    console.log(output);

    【讨论】:

    【解决方案2】:

    您可以使用reduce

    遍历 arr 并为 arr 中的每个元素循环获取所需的索引值并将其推送到 op。

    let a = [["", "2", "", ""], ["1", "3", "", ""], ["", "", "4", ""]]
    
    function getIndex(arr,index){
      return arr.reduce((op,inp) => {
        let val = inp.find((e,i) => i === index )
        op.push(val)
        return op
      },[])
    }
    
    console.log(getIndex(a,0))
    console.log(getIndex(a,1))

    【讨论】:

    【解决方案3】:

    获取第一个索引:

    const result = Array.map(a=>a[0]);
    

    result 将包含嵌套数组中所有元素的第一个索引。这通过遍历数组并获取第一个索引元素来工作

    【讨论】:

    【解决方案4】:

    使用 lodash,您可以将索引用作迭代对象:

    const result = _.map(a, 1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-09
      • 2018-01-17
      相关资源
      最近更新 更多