NodeJS 在lodash中合并多个数组

eqzww0vc  于 2023-04-05  发布在  Node.js
关注(0)|答案(4)|浏览(221)

我想把这些数组合并成一个具有唯一值的数组。不要重复的值。

0:Array(2) ["General Fitness", "Health & Fitness"]
1:Array(2) ["Cardiovascular", "Meditation"]
2:Array(3) ["Health & Fitness", "Cardiovascular", "General Fitness"]
3:Array(1) ["Cardiovascular"]

我期待这个答案:

["General Fitness", "Health & Fitness", "Cardiovascular", "Meditation"]
mwg9r5ms

mwg9r5ms1#

使用lodash,你可以使用_.union()_.spread()来生成一个函数,该函数可以展平为一个具有唯一值的数组:

const fn = _.spread(_.union);

const arrs = [ 
  ["General Fitness", "Health & Fitness"],
  ["Cardiovascular", "Meditation"],
  ["Health & Fitness", "Cardiovascular", "General Fitness"],
  ["Cardiovascular"]
];

const result = fn(arrs);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

使用ES6,你可以flatten数组,并通过将其传递给Setspreading返回数组来使结果唯一:

const arrs = [ 
  ["General Fitness", "Health & Fitness"],
  ["Cardiovascular", "Meditation"],
  ["Health & Fitness", "Cardiovascular", "General Fitness"],
  ["Cardiovascular"]
];

const result = [...new Set(arrs.flat())];

console.log(result);
xlpyo6sf

xlpyo6sf2#

const arrs = [ 
  ["General Fitness", "Health & Fitness"],
  ["Cardiovascular", "Meditation"],
  ["Health & Fitness", "Cardiovascular", "General Fitness"],
  ["Cardiovascular"]
];

const result = _.uniq(_.flatten(arrs));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
uhry853o

uhry853o3#

使用工会

var object =  ["General Fitness", "Health & Fitness"];
var other =  ["Cardiovascular", "Health & Fitness", "Meditation"]
 
_.union(object, other);

// ["General Fitness", "Health & Fitness", "Cardiovascular", "Meditation"]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
7lrncoxx

7lrncoxx4#

简单地使用lodash flatten method

const arrs = [ 
  ["General Fitness", "Health & Fitness"],
  ["Cardiovascular", "Meditation"],
  ["Health & Fitness", "Cardiovascular", "General Fitness"],
  ["Cardiovascular"]
];

result = _.flatten(arrs);

console.log(result);

相关问题