var data = [ {userId: 8, title: 'title1'}, {userId: 11, title: 'other'}, {userId: 15, title: null}, {userId: 19, title: 'title2'} ];查找data中, [{ userId: 19, title: 'title2'}, { userId: 8, title: 'title1' }]并进行排序
时间: 2023-04-10 21:02:26 浏览: 77
可以使用以下代码实现:
const targetData = [{ userId: 19, title: 'title2' }, { userId: 8, title: 'title1' }];
const sortedData = data.filter(item => targetData.some(target => target.userId === item.userId && target.title === item.title)).sort((a, b) => targetData.findIndex(target => target.userId === a.userId && target.title === a.title) - targetData.findIndex(target => target.userId === b.userId && target.title === b.title));
这段代码首先使用 filter 方法筛选出 data 中与 targetData 相同的元素,然后使用 sort 方法根据 targetData 中元素的顺序进行排序。
相关问题
在var data=[{user:8,title:'aa'},{user:10},{user:11,title:'bb'},]中查找,输出[{user:8,title:'aa'},{user:11,title:'bb'}]并进行排序的方法
可以使用 JavaScript 的 filter() 方法和 sort() 方法来实现。代码如下:
```
var data=[{user:8,title:'aa'},{user:10},{user:11,title:'bb'},];
var filteredData = data.filter(function(item) {
return item.title !== undefined;
});
var sortedData = filteredData.sort(function(a, b) {
return a.user - b.user;
});
console.log(sortedData);
```
输出结果为:
```
[{user:8,title:'aa'},{user:11,title:'bb'}]
```
在var data=[{user:8,title:'aa'},{user:10,title:'cc'},{user:11,title:'bb'},]中查找,输出[{user:8,title:'aa'},{user:11,title:'bb'}]并进行排序的方法
可以使用数组的 filter 方法来查找符合条件的元素,然后使用 sort 方法进行排序。具体代码如下:
```javascript
var data=[{user:8,title:'aa'},{user:10,title:'cc'},{user:11,title:'bb'},];
var filteredData = data.filter(function(item) {
return item.user === 8 || item.user === 11;
});
filteredData.sort(function(a, b) {
return a.user - b.user;
});
console.log(filteredData);
```
输出结果为:
```
[{user:8,title:'aa'},{user:11,title:'bb'}]
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)