🍍
配列の重複問題
文字列が重複していたら、その配列をあぶりだす!
// 名前の配列
const names = [
"Jhon",
"Tom",
"Alice",
"Tom",
"Bob",
"Jhon"
];
- step1. 配列をループ分で回し表示する
//step1
for(const strEl of names){
console.log(strEl);
}
- step2. step1を関数にして、再度確認
//step1 -> step2
const duplicate = array => {
for(const strEl of names){
console.log(strEl);
}
}
duplicate(names);
- step3. 出てきたものを格納する変数を宣言
- step4. 重複したものを格納する変数を宣言
//step3, step4
const seen = new Set();
const dup = new Set();
//step1 -> step2
const duplicate = array => {
for(const strEl of names){
console.log(strEl);
}
}
duplicate(names);
- step5. もし、出てきたものの変数にその文字列がすでに入っているなら、dupにその文字列を追加
- step6. もし、出てきたものの変数にその文字列がまだ入っていないなら、seenにその文字列を追加
//step3, step4
const seen = new Set();
const dup =new Set();
//step1 -> step2
const duplicate = array => {
for(const strEl of names){
//step5
if(seen.has(strEl))
{
dup.add(strEl);
}
//step6
else
{
seen.add(strEl);
}
}
}
duplicate(names);
- step7. 今回は、重複ている文字列を返す(新しい配列に格納する)
//step3, step4
const seen = new Set();
const dup =new Set();
//step1 -> step2
const duplicate = array => {
for(const strEl of names){
//step5
if(seen.has(strEl))
{
dup.add(strEl);
}
//step6
else
{
seen.add(strEl);
}
}
return Array.from(dup);
}
console.log(duplicate(names));
参照
Discussion