过滤重复的记录,并使用js将其推入带有附加条件的数组



I希望过滤城市和州不相同的对象列表,然后从过滤后的温度低于40的对象中创建一个城市列表。但条件是州和城市不应该是相同的

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代码:

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 );

您应该在代码中尝试一下!

只要用箭头函数把条件放在result语句中,就可以开始了。

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);

这将检查citystate值的唯一性,并处理您的附加条件。它不会添加与数组中任何其他对象具有相同city和相同state值的值。

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);

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);

因为您想过滤掉城市和州名称相同且温度大于40的对象。

此外,如果原始arr有重复的对象,并且您想要一个唯一对象数组。您可以使用:

const result = arr.filter(data => data.temp < 40 && data.state !== data.city);
for (let i = 0; i < result.length; ++i) {
for (let j = 0; j < result.length; ++j) {
if ( i !== j && 
result[i].city === result[j].city && 
result[i].state === result[j].state && 
result[i].temp === result[j].temp
) {
result.splice(j, 1);
}
}
}

最新更新