필터링 후 배열을 하나의 배열로 병합


14

위치 배열 만 취하는 객체 배열이 있습니다. 내 목표는이 위치 배열을 하나의 배열로 병합하는 것이지만 그렇게하지 않으면 빈 배열이됩니다. 이것이 내가하는 방법입니다.

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'];

답변:


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/…
Mihai Alexandru-Ionut

7

당신은 시도 할 수 있습니다 flatMap():

flatMap()방법은 먼저 매핑 함수를 사용하여 각 요소를 매핑 한 다음 결과를 새 배열로 병합합니다. 이것은 동일 map()a로 다음 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원하는 속성으로 a 를 타카 할 수 있습니다. 속성이 제공되지 않으면 기본 배열을 추가하십시오 || [].

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 }));
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.