gpt4 book ai didi

javascript - Backbone.js:比较集合中的模型属性

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:49:47 25 4
gpt4 key购买 nike

我有一个无限范围的集合(可以是0,可以是1000,可以是百万)。我需要搜索集合中每个模型的属性并返回相同的属性(及其值)。

例如,如果我的收藏中有以下三个模型:

modelOne:
color: "red"
age: 10
size: "large"

modelTwo:
color: "red"
age: 11
size: "medium"

modelThree:
color: "red"
age: 9
size: "large"

我需要应用程序返回 color: "red"(或其他可以解析的推导),因为它是所有三个模型中唯一相同的属性。

编辑 John Munsch 的解决方案效果很好,但现在要求发生了变化,一些属性现在可以是数组。有没有办法比较作为数组的常规属性、属性?

新代码示例:

modelOne:
color: "red"
age: 10
sizes: ["small", "large"]

modelTwo:
color: "red"
age: 9
sizes: ["small", "large"]

最佳答案

这是一个带有我的答案版本的快速 jsFiddle:http://jsfiddle.net/JohnMunsch/3NMGD/

注意:jsFiddle 和下面的代码都已更新以反射(reflect)问题的更改要求。

var model = [
{
color: "red",
age: 10,
size: [ "small", "large" ]
},
{
color: "red",
age: 11,
size: [ "small", "large" ]
},
{
color: "red",
age: 9,
size: [ "small", "large" ]
}
];

function findCommonalities(data) {
if (data.length > 0) {
// It's safe enough to get the list of keys from the very first
// element. If the later ones differ, you know that the keys they
// had but the first element didn't are guaranteed not to be in
// the common set anyway because the first element didn't
// have them.
var keys = _.keys(data[0]);
var commonalities = { };

_.each(keys,
function (key) {
var values = _.pluck(data, key);

if (values.length == data.length) {
// Sadly calling _.uniq() won't work when the values
// plucked out are arrays themselves. It calls ===
// and that's not sufficient for arrays.
if (_.isArray(values[0])) {
// However, we can get a little tricky here.
// What if we _.zip() together all of the arrays
// (assuming the ordering for each array is the
// same) then we'll end up with an array of
// arrays where each one can again be tested
// with _.uniq() because each one will contain
// the same value taken from each array.
var zippedValues = _.zip(values);
console.log("zippedValues", zippedValues);

if (!_.find(zippedValues,
function (zippedValue) {
var uniqueValues = _.uniq(zippedValue);

// Note: This test is the inverse of the
// one below. We're trying to find any
// array that has more than one value in
// it. If we do then there's some
// variance.
return uniqueValues.length != 1;
})) {
// We didn't find any arrays that had any
// variance so we want this as well.
commonalities[key] = values[0];
}
} else {
var uniqueValues = _.uniq(values);

if (uniqueValues.length == 1) {
commonalities[key] = uniqueValues[0];
}
}
}
}
);

return commonalities;
} else {
return { };
}
}

console.log("commonalities: ", findCommonalities(model));

对于少量键和少量项目,性能似乎很好,但您需要使用一百万条记录和大量键来测试它。

关于javascript - Backbone.js:比较集合中的模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10335617/

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