I wan to filter the list of objects where city and state are not same, and then create a list of cities out of the filtered objects where temperature is less than 40. but condition is both sate and city should not be same
let arr = [
{
city:"chennai",
state: "tamilnadu",
temp: 44
},
{
city:"coimbator",
state: "tamilnadu",
temp: 39
},
{
city:"mumbai",
state: "maharashtra",
temp: 32
},
{
city:"delhi",
state: "delhi",
temp: 24
},
{
city:"kolkata",
state: "west bengal",
temp: 28
}
];
Javascript code:
const uniqueStateCity = [];
const unique = arr.filter(element => {
const isDuplicate = uniqueStateCity.includes(element.city);
if (!isDuplicate) {
if(element.temp < 40)
{
uniqueStateCity.push(element.city );
return true;
}
}
return false;
});
console.log(unique );
You should try this in your code!
just put condition in the result statement with arrow function and you are good to go.
let arr = [
{
city: "chennai",
state: "tamilnadu",
temp: 44,
},
{
city: "coimbator",
state: "tamilnadu",
temp: 39,
},
{
city: "mumbai",
state: "maharashtra",
temp: 32,
},
{
city: "delhi",
state: "delhi",
temp: 24,
},
{
city: "kolkata",
state: "west bengal",
temp: 28,
},
];
const result = arr.filter((data) => data.temp < 40 && data.state !== data.city);
const data = result.map((x) => x.city);
console.log(data);
let arr = [
{
city: "chennai",
state: "tamilnadu",
temp: 44,
},
{
city: "coimbator",
state: "tamilnadu",
temp: 39,
},
{
city: "mumbai",
state: "maharashtra",
temp: 32,
},
{
city: "mumbai",
state: "maharashtra",
temp: 32,
},
{
city: "delhi",
state: "delhi",
temp: 24,
},
{
city: "kolkata",
state: "west bengal",
temp: 28,
},
];
const result = [
...new Set(
arr.filter((data) => data.temp < 40 && data.state !== data.city).map((data) => data.city)
)
];
console.log(result);
This checks for uniqueness of city and state values and also handles your additional conditions. It will not add values which have the same city and the same state value as any other object in the array.
const arr = [
{
city: "chennai",
state: "tamilnadu",
temp: 44,
},
{
city: "coimbator",
state: "tamilnadu",
temp: 39,
},
{
city: "mumbai",
state: "maharashtra",
temp: 32,
},
{
city: "mumbai",
state: "maharashtra",
temp: 32,
},
{
city: "delhi",
state: "delhi",
temp: 24,
},
{
city: "kolkata",
state: "west bengal",
temp: 28,
}
];
const result = arr.reduce((all, cur) => {
if (
all.findIndex((c) => c.city === cur.city && c.state === cur.state) < 0 &&
cur.state !== cur.city &&
cur.temp < 40
) {
all.push(cur);
}
return all;
}, []);
console.log(result);