フィルタリング後に配列を1つの配列にマージする


14

ロケーションの配列のみを取得するオブジェクトの配列があります。私の目標は、これらの場所の配列を1つの配列にマージすることですが、そうすることができず、空の配列を取得します。これが私のやり方です:

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/...
ミハイアレクサンドル-はIonut

7

あなたは試すことができますflatMap()

このflatMap()メソッドは、最初にマッピング関数を使用して各要素をマップし、次に結果を新しい配列にフラット化します。aのmap()flat()depth 1が続くのと同じですが、flatMap()両方を1つのメソッドにマージする方がわずかに効率的であるため、たいていは非常に便利です。

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は、ポリフィルがないと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.