Hi I have some problem fetching specific information based on user choice. I want to fetch newsAPI , inside array there are objects contain countries. The user selects the country he wants by using dropdown, but there is an iterative country when I using map() it passes on all countries with duplicates, I tried to delete the duplicate, but it didn't work I used reduce() but it didn't work either. Are there any tips and suggestions, maybe there is something I missed.
html:
<html>
<div class="ui container" id="seachCountry"></div>
</html>
Script:
<script>
const apikey = 'https://newsapi.org/v2/top-headlines/sources?category=sports&apiKey=b23fd6aac9c44682abb9580dae85d23f';
async function getNews(){
const response = await fetch(apikey);
const data = await response.json();
printCards(data)
}
function printCards(data) {
const header = document.querySelector('#seachCountry');
//Inside "header.innerHTMI", I put map() function to pass all items but I couldn't prevent duplicates
header.innerHTML = `
<select class='ui fluid selection dropdown select' onchange="getCountry(this.value)">
<option>select the country</option>
${data.sources.map( countryName => `<option>${countryName.country}</option>`)}
</select>`
// print all country name using map and dispaly it to user in dropdown WIHT deplicate country name
}
async function getCountry(e){
if ( e !== 'select the country'){
//Another Fetch based on user choice
const response = await fetch(`${apikey}&country=${e}`)
const data = await response.json();
console.log(data.sources)
//It only shows the information of the country in which the user is interested
document.getElementById("output").innerHTML = data.sources.map(countryName =>
`<div >
<div >
<h4 >${countryName.name}</h4>
</div>
<div >
<div >${countryName.description}</div>
</div>
<div >
<span>
<a href=${countryName.url} target="_blank" >Read more</a>
</span>
</div>
</div>`)
}
}
getNews()
</script>
Look at this Picture to Clarify the Problem
CodePudding user response:
You can filter the array to have only distinct values by using this function:
source.filter((item, index) => source.indexOf(item) === index);
So, in your case, where you are mapping to a list of option
s, it will be something like this:
function printCards(data) {
const header = document.querySelector('#seachCountry');
const countries = data.sources.map(cn => cn.country);
const distinctCountries = countries.filter((country, index) => countries.indexOf(country) === index);
header.innerHTML = `
<select class='ui fluid selection dropdown select' onchange="getCountry(this.value)">
<option>select the country</option>
${distinctCountries.map(country => `<option>${country}</option>`)}
</select>`;
}