본문 바로가기
Javascript

array object methods

by peach1227 2025. 1. 16.
<style>
p {background-color:rgba(10, 10, 10, .1);}
span {background-color:rgba(255,0,0,1);}
</style>

<div id="div1"><p id="p1">
An apple is a round, edible fruit produced by an apple tree (Malus spp., among them the domestic or orchard apple; Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the genus Malus. The tree originated in Central Asia, where its wild ancestor, Malus sieversii, is still found. Apples have been grown for thousands of years in Eurasia and were introduced to North America by European colonists. Apples have religious and mythological significance in many cultures, including Norse, Greek, and European Christian tradition.
</p>
<p id="p2"></p>
<p id="p3"></p>

</div>

<script>

const obj={};
var arr=p1.textContent.split(/\s+/).map(i => i.toUpperCase()).sort();//regular expression
console.log(arr);
arr.forEach((item,i) => {

if(!Object.keys(obj).includes(item[0])){
obj[item[0]]=[];

}else{if(!obj[item[0]].includes(item)) obj[item[0]].push(item);}//remove duplicates;
});

//
for (const i in obj){
if(!obj.hasOwnProperty(i)) continue;
console.log(obj[i]);
p2.innerHTML +='<br><span>'+i+'</span>('+obj[i].length+')'+"<br>"+obj[i].map(i => "<li>"+i+"</li>").join(" ")+'<br>';
}

</script>

An apple is a round, edible fruit produced by an apple tree (Malus spp., among them the domestic or orchard apple; Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the genus Malus. The tree originated in Central Asia, where its wild ancestor, Malus sieversii, is still found. Apples have been grown for thousands of years in Eurasia and were introduced to North America by European colonists. Apples have religious and mythological significance in many cultures, including Norse, Greek, and European Christian tradition.

반응형