I have react project and in that have a javascript array of object similar to given below and in that object it has a value called category
.
const data = [{
"id": 1,
"item": "760",
"price": "$609.05",
"category": "BMW"
}, {
"id": 2,
"item": "Frontier",
"price": "$317.89",
"category": "Nissan"
}, {
"id": 3,
"item": "Odyssey",
"price": "$603.64",
"category": "BMW"
}]
Im mapping through the list and displaying the category
as shown below.
{data.map(item => (<span>{item.category}</span>))}
Here, the category
duplicates and display several times when there are several similar items. Considering the given data
list, the category
BMW
display twice.
What I want is, even if there are multiple similar categories
, I only want to display once. Is this possible and how can I do it?
CodePudding user response:
You could add your categories into a Set
const data = [{
"id": 1,
"item": "760",
"price": "$609.05",
"category": "BMW"
}, {
"id": 2,
"item": "Frontier",
"price": "$317.89",
"category": "Nissan"
}, {
"id": 3,
"item": "Odyssey",
"price": "$603.64",
"category": "BMW"
}]
let categories = new Set()
data.forEach(entry => {categories.add(entry.category) })
categories.forEach(cat => console.log(cat))
CodePudding user response:
There can be various ways to reach the desired result. I would do it with a Set()
and destructuring syntax:
{[...new Set(data.map(item => (<span>{item.category}</span>)))]}
const data = [{
"id": 1,
"item": "760",
"price": "$609.05",
"category": "BMW"
}, {
"id": 2,
"item": "Frontier",
"price": "$317.89",
"category": "Nissan"
}, {
"id": 3,
"item": "Odyssey",
"price": "$603.64",
"category": "BMW"
}]
const newData = [...new Set(data.map(item => ("<span>" item.category "</span>")))]
console.log(newData);
CodePudding user response:
you can use {data.find(item => (<span>{item.category}</span>))}
. The find()
method returns the first element in the provided array that satisfies the provided testing function
CodePudding user response:
You can use the filter
let array= data.filter((v,i,a)=>a.findIndex(v2=>(v2.category===v.category))===i)
and
{array.map(item => (<span>{item.category}</span>))}
CodePudding user response:
const data = [{
"id": 1,
"item": "760",
"price": "$609.05",
"category": "BMW"
}, {
"id": 2,
"item": "Frontier",
"price": "$317.89",
"category": "Nissan"
}, {
"id": 3,
"item": "Odyssey",
"price": "$603.64",
"category": "BMW"
}]
function getUniqueArrayBy(arr, key) {
return [...new Map(arr.map(item => [item[key], item])).values()]
}
const filtered = getUniqueArrayBy(data, 'category');
console.log(filtered);
CodePudding user response:
Use native methods .reduce
and .map
of Array
in chain.
const categories = data.reduce((acc, {category}) => {
if (!acc.includes(category)) { // check if there's not such value in accumulator
acc.push(category); // adding category
}
return acc; // returning value
}, []) // [] is an accumulator value
.map(category => <span>{category}</span>); // iterating over result
Piece a cake.