过滤后将阵列合并到一个阵列


14

我有对象数组,我只用位置数组。我的目标是将这些locations数组合并为一个数组,但是我这样做并没有得到空数组。这是我的方法:

let results = [{
    id: '1',
    locations: ['aaaa', 'bbbbbb', 'cccccc']
  },
  {
    id: '2',
    locations: []
  },
  {
    id: '3',
    locations: ['ddd', 'aaadsad', 'sefd']
  },
  {
    id: '4',
    locations: ['ffff', 'eeee', 'sfdsfsd']
  },
];
const locationIds = [].concat.apply([], ...results.filter(s => s.locations && s.locations.length > 0).map(({
  locations
}) => ({
  locations
})));

console.log(locationIds);

我在这里做错了什么?结果应该是 ['aaaa', 'bbbbbb', 'cccccc', 'ddd', 'aaadsad', 'sefd', 'ffff', 'eeee', 'sfdsfsd'];

Answers:


9

您不需要filter这里。map通过传递回调提供的函数来使用方法,该函数适用于数组中的每个项目。

let results = [{ id: '1', locations: ['aaaa', 'bbbbbb', 'cccccc'] }, { id: '2', locations: [] }, { id: '3', locations: ['ddd', 'aaadsad', 'sefd'] }, { id: '4', locations: ['ffff', 'eeee', 'sfdsfsd'] }, ];

const locationIds = [].concat(...results.map(s => s.locations));

console.log(locationIds);


1
@ user122222,不客气!你可以创建自己的实现flatMap:喜欢这里stackoverflow.com/questions/39837678/...
米哈伊亚历-约努茨

7

您可以尝试flatMap()

flatMap()方法首先使用映射函数映射每个元素,然后将结果展平为新数组。它等同于一个map()接着一个flat()深度为1,但flatMap()往往是相当有用的,因为这两个合并成一个方法会更有效。

let results = [{
    id: '1',
    locations: ['aaaa', 'bbbbbb', 'cccccc']
  },
  {
    id: '2',
    locations: []
  },
  {
    id: '3',
    locations: ['ddd', 'aaadsad', 'sefd']
  },
  {
    id: '4',
    locations: ['ffff', 'eeee', 'sfdsfsd']
  },
];
const locationIds = results.flatMap(i => i.locations);
console.log(locationIds);


6

您可以将其Array#flatMap与通缉的财产合在一起。如果未提供该属性,则添加默认数组|| []

let results = [{ id: '1', locations: ['aaaa', 'bbbbbb', 'cccccc'] }, { id: '2', locations: [] }, { id: '3', locations: ['ddd', 'aaadsad', 'sefd'] }, { id: '4', locations: ['ffff', 'eeee', 'sfdsfsd'] }],
    locationIds = results.flatMap(({ locations }) => locations);

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


2
值得一提的是.flatMap在没有polyfill的Edge和IE中不起作用。
Zydnar

3

也可以使用Array.prototype中的Reduce函数来解决。

var newResults = results.reduce(function(acc, curr) {
    return acc.concat(curr.locations)
  },[]
)

希望这可以帮助


2

我花了太多时间在这个问题上,以至于没有发布自己的解决方案,这对我来说是一个有趣的难题,尽管其他答案无疑更高效和可读。它使用与原始帖子相同的策略,这可能有助于指出错误所在。

const locationIds = [].concat
                    .apply([], results.filter(result => 
                    result.locations && result.locations.length > 0)
                    .map(result => { return result.locations }));
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.