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

时间:2020-02-01 10:10:14

标签: javascript arrays typescript

我有对象数组,我只用位置数组。我的目标是将这些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'];

5 个答案:

答案 0 :(得分: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 :(得分:7)

您可以尝试使用flatMap()

flatMap()方法首先使用映射函数映射每个元素,然后将结果展平为新数组。它与map()后跟 depth1 flat()相同,但是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);

答案 2 :(得分: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; }

答案 3 :(得分:3)

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

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

希望这会有所帮助

答案 4 :(得分:2)

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

const locationIds = [].concat
                    .apply([], results.filter(result => 
                    result.locations && result.locations.length > 0)
                    .map(result => { return result.locations }));