gpt4 book ai didi

javascript - angularjs验证重复项并设置更大的重复项

转载 作者:行者123 更新时间:2023-12-01 02:35:53 24 4
gpt4 key购买 nike

我有这段代码,我正在检查重复项,如果重复,它有 isDuplicate bool 值,但我想扩展我的代码并比较另一个属性,即 colorId 并设置 isBigger 属性,以获取较大的属性:)您有什么建议吗?非常感谢您

这是我的代码:

$scope.verifyDuplicate = function() {
var names = [{
"order": 1,
"name": "a",
"shortName": "a",
"isDuplicate": false,
"categoryId": 15070,
"colorId": 50
}, {
"order": 2,
"name": "s",
"shortName": "s",
"categoryId": 15071,
"colorId": 51
}, {
"order": 3,
"name": "h",
"shortName": "g",
"focused": 1513262627570,
"isDuplicate": true,
"categoryId": 15074,
"colorId": 54
}, {
"order": 4,
"name": "h",
"shortName": "h",
"isDuplicate": true,
"categoryId": 15075,
"colorId": 59
}];
var sorted, i;

sorted = names.concat().sort(function(a, b) {
if (a.name > b.name)
return 1;
if (a.name < b.name)
return -1;
return 0;
});
for (i = 0; i < names.length; i++) {
if (sorted[i].name !== '') {
sorted[i].isDuplicate = ((sorted[i - 1] && sorted[i - 1].name === sorted[i].name)) || ((sorted[i + 1] && sorted[i + 1].name === sorted[i].name));
}
}
};

最佳答案

您可以引入一个通用函数,使用以下函数根据任何键对对象数组进行排序 -

$scope.sortByKey = function(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
});
};

使用此函数,您可以根据任意键对对象数组进行排序,并将属性“isLargest”设置为 true。您可以检查下面的代码片段。

$scope.verifyDuplicate = function() {
var names = [{
"order": 1,
"name": "a",
"shortName": "a",
"isDuplicate": false,
"categoryId": 15070,
"colorId": 50
}, {
"order": 2,
"name": "s",
"shortName": "s",
"categoryId": 15071,
"colorId": 51
}, {
"order": 3,
"name": "h",
"shortName": "g",
"focused": 1513262627570,
"isDuplicate": true,
"categoryId": 15074,
"colorId": 54
}, {
"order": 4,
"name": "h",
"shortName": "h",
"isDuplicate": true,
"categoryId": 15075,
"colorId": 59
}];

var sorted;
sorted = $scope.sortByKey(names , "colorId");

//To check if the multiple object has largest value
for(var i = 0; i< sorted.length;i++){
if(sorted[i] === sorted[0]) sorted[i]["isLargestColorId"] = true;
else break;
}

};

关于javascript - angularjs验证重复项并设置更大的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47921764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com