我想要过滤城市和州不同的对象列表,然后从过滤的对象中创建温度低于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 );

推荐答案

这将判断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);

Javascript相关问答推荐

我应该在redux reducer中调用其他reducer函数吗?

if/else JavaScript中的条件行为

IMDB使用 puppeteer 加载更多按钮(nodejs)

在页面上滚动 timeshift 动垂直滚动条

角色 map 集/spritebook动画,用户输入不停止在键上相位器3

如何从一个列表中创建一个2列的表?

Chart.js 4.4.2,当悬停在一个数据点上时,如何在工具提示中拥有多个数据点/标签?

如何控制Reaction路由加载器中的错误状态?

编剧如何获得一个div内的所有链接,然后判断每个链接是否都会得到200?

material UI按钮组样式props 不反射

IF语句的计算结果与实际情况相反

使用getBorbingClientRect()更改绝对元素位置

打字脚本中方括号符号属性访问和拾取实用程序的区别

在Vercel中部署Next.js项目时获取`ReferenceError:未定义文档`

如何在脚本编译后直接将RxJ模块导入浏览器(无需Angel、webpack、LiteServer)

如何使用[ModelJSON,ArrayBuffer]调用tf.loadGraphModelSync

如何在下一个js中更改每个标记APEXCHARTS图表的 colored颜色

将以前缓存的 Select 器与querySelector()一起使用

如何判断字符串是否只包含特定字符串

动画可以在Chrome上运行,但不能在Safari上运行