配列JavaScriptの要素でグループ化
このようなオブジェクトの配列があるとします-
const arr = [
{"name": "toto", "uuid": 1111},
{"name": "tata", "uuid": 2222},
{"name": "titi", "uuid": 1111}
]; オブジェクトを、uuidプロパティの値が類似している配列の個別の配列に分割するJavaScript関数を作成する必要があります。
出力
したがって、出力は次のようになります-
const output = [
[
{"name": "toto", "uuid": 1111},
{"name": "titi", "uuid": 1111}
],
[
{"name": "tata", "uuid": 2222}
]
]; このためのコードは-
になりますconst arr = [
{"name": "toto", "uuid": 1111},
{"name": "tata", "uuid": 2222},
{"name": "titi", "uuid": 1111}
];
const groupByElement = arr => {
const hash = Object.create(null),
result = [];
arr.forEach(el => {
if (!hash[el.uuid]) {
hash[el.uuid] = [];
result.push(hash[el.uuid]);
};
hash[el.uuid].push(el);
});
return result;
};
console.log(groupByElement(arr)); 出力
コンソールの出力-
[
[ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ],
[ { name: 'tata', uuid: 2222 } ]
] -
JavaScriptでIDごとにオブジェクトの配列をグループ化する方法は?
以下は、JavaScriptでオブジェクトの配列をIDでグループ化するコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>
-
配列の最後の要素を出力するJavaScriptコード
以下は、配列の最後の要素を出力するコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> bod