从Array of Array中获取唯一元素

时间:2018-05-05 18:50:41

标签: javascript arrays node.js list

我有一个String数组的数组,我想从该数组中获取忽略大小写的唯一元素。我该怎么取 例如:

数组列表:

[
       ["java,C,Node,ReactJs"]
        ["c","Spring"]
        ["undefined"]
        ["asdja"]
        ["Java","Spring"]
        ["adjasjh"]
        ["adjasjh"]
        ["java"] 
]

ExpectedList:

[java,C,node,reactjs,spring,..]

4 个答案:

答案 0 :(得分:2)

Join数组,用逗号更改to lower casesplit,转换为Set以获取唯一字词,然后spread返回到阵列:



const arr = [["java,NO,C,Node,ReactJs"],["c","Spring"],["undefined"],["asdja"],["Java","Spring"],["adjasjh", "Spring-roll"],["adjasjh"],["java", "javascript", "java-script"]];

const result = [...new Set(arr.join().toLowerCase().split(','))];

console.log(result);




较旧的答案 - 在所有情况下都不会工作:

您可以join数组数组,并使用String.match()negative lookahead RegExp来获取唯一字符串:



const arr = [["java,NO,C,Node,ReactJs"],["c","Spring"],["undefined"],["asdja"],["Java","Spring"],["adjasjh", "Spring-roll"],["adjasjh"],["java", "javascript", "java-script"]];

const result = arr.join()
  .match(/([^,]+\b)(?!.+\1[,|$])/ig);

console.log(result);




答案 1 :(得分:1)

您可以使用reducemap方法迭代数组和单词,并使用Set最终返回唯一元素数组。



const array = [["java,C,Node,ReactJs"], ["c","Spring"], ["undefined"], ["asdja"], ["Java","Spring"], ["adjasjh"], ["adjasjh"], ["java"] ]

const result = [...new Set(array.reduce((r, e) => {
  return r.concat(...e.map(s => s.split(',').map(w => w.toLowerCase())))
}, []))]
console.log(result)




答案 2 :(得分:1)

您可以平展数据并使用Map保留第一个唯一值而不会改变它。

const flat = (r, a) => Array.isArray(a) ? a.reduce(flat, r) : r.concat(a.split(','));

var data = [["java,C,Node,ReactJs"], ["c", "Spring"], ["undefined"], ["asdja"], ["Java", "Spring"], ["adjasjh"], ["adjasjh"], ["java"]],
    unique = Array.from(data
        .reduce(flat, [])
        .reduce((m, v) => ((l => m.has(l) || m.set(l, v))(v.toLowerCase()), m), new Map)
        .values()
    );

console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:1)

您可以展平数组,将每个值转换为小写,使用Set删除重复项,然后Array.from将其转换回数组。

如果您的["java,C,Node,ReactJs"]实际上是:["java","C","Node","ReactJs"],您可以这样做:



const array = [
       ["java","C","Node","ReactJs"],
       ["c","Spring"],
       ["undefined"],
       ["asdja"],
       ["Java","Spring"],
       ["adjasjh"],
       ["adjasjh"],
       ["java"] 
];


const unique = Array.from(
  new Set([].concat.apply([], array).map(item => item.toLowerCase()))
  //       ^^^ flatten array     
);

console.log(unique);