|
const persons = [ |
|
{ name: "John", age: 35 }, |
|
{ name: "Anne", age: 24 }, |
|
{ name: "Tom", age: 41 }, |
|
{ name: "Andrew", age: 55 }, |
|
{ name: "Mary", age: 18 }, |
|
]; |
|
|
|
// Get all HTML Tags and Class |
|
const allData = document.getElementsByClassName('all-data'); |
|
const filterLoop = document.getElementsByClassName('normal-loop'); |
|
const filterNormal = document.getElementsByClassName('filter-normal'); |
|
const filterArrow = document.getElementsByClassName('filter-arrow'); |
|
|
|
// Show all data in all-data div |
|
const listAll = document.createElement('ul'); |
|
const para1 = document.createElement('p'); |
|
|
|
para1.textContent = "All data before filtered:"; |
|
for(let i = 0; i < persons.length; i++) { |
|
const listItem1 = document.createElement('li'); |
|
listItem1.textContent = `Name: ${persons[i].name}. Age: ${persons[i].age}`; |
|
listAll.appendChild(listItem1); |
|
} |
|
|
|
allData[0].appendChild(para1); |
|
allData[0].appendChild(listAll); |
|
|
|
// Filtering using normal loop |
|
const listNormalLoop = document.createElement('ul'); |
|
const para2 = document.createElement('p'); |
|
|
|
para2.textContent = "Data filtered using normal loop:"; |
|
|
|
let filtered = []; |
|
for(let i = 0; i < persons.length; i++ ) { |
|
if(persons[i].age > 30) { |
|
filtered.push(persons[i]); |
|
} else { |
|
continue; |
|
} |
|
} |
|
|
|
for(let i = 0; i < filtered.length; i++) { |
|
const listItem2 = document.createElement('li'); |
|
listItem2.textContent = `Name: ${filtered[i].name}. Age: ${filtered[i].age}`; |
|
listNormalLoop.appendChild(listItem2); |
|
} |
|
|
|
filterLoop[0].appendChild(para2); |
|
filterLoop[0].appendChild(listNormalLoop); |
|
|
|
// filtering using filter method and normal function |
|
const listFilterNormal = document.createElement('ul'); |
|
const para3 = document.createElement('p'); |
|
|
|
para3.textContent = "Data filtered using filter and normal function:"; |
|
|
|
let filteredNormal = persons.filter(function(person) { |
|
if(person.age > 30) return person; |
|
}); |
|
|
|
for(let i = 0; i < filteredNormal.length; i++) { |
|
const listItem3 = document.createElement('li'); |
|
listItem3.textContent = `Name: ${filteredNormal[i].name}. Age: ${filteredNormal[i].age}`; |
|
listFilterNormal.appendChild(listItem3); |
|
} |
|
|
|
filterNormal[0].appendChild(para3); |
|
filterNormal[0].appendChild(listFilterNormal); |
|
|
|
// Filtering using filter method and arrow function |
|
const filteredArrow = persons.filter((person) => person.age > 30); |
|
console.log(filteredArrow); |