减少重复值

时间:2017-03-02 08:24:53

标签: javascript

我有这个:

BasesFunctions.AllAgents = function(self){
    self.agents = self.datas.reduce(function (all, item, index) {
        item[self.valORname] == self.datas.valORname;
        all.push(item[self.valORname]);
        return all;
    }, []);
};

我的问题很简单,这个函数返回:

Array [ "BLABLA", "TEST", "HONORE", "SPONGEBOB", "PATRIC", "AVEA", "TEST", "HONORE", "PATRIC", "TEST", 16 more… ]

我希望当我的值存在时不要推入我的数组,只需要索引1,2,3的不同值....我不希望重复我的价值[&#34; BLABLA&#34;,&#34; TEST&#34; &#34; HONORE&#34; < / strong>,&#34; SPONGEBOB&#34;,&#34; PATRIC&#34; ,&#34; AVEA&#34;,&#34; TEST&#34; < / strong>,&#34; HONORE&#34; &#34; PATRIC&#34; &#34; TEST&#34; ,16更多......]

你能帮帮我吗?请致谢

谢谢所有我有答案^^非常简单我只需要像这样使用IndexOf():

BasesFunctions.AllAgents = function(self){
    self.agents = self.datas.reduce(function (all, item, index) {
        item[self.valORname] == self.datas.valORname;
        if(all.indexOf(item[self.valORname]) === -1)
        {
        all.push(item[self.valORname]);
        }
        return all;
    }, []);
};

2 个答案:

答案 0 :(得分:0)

您可以扩展数组的原型,如:

// check if an element exists in array using a comparison function
// comparer : function(currentElement)
Array.prototype.inArray = function(comparer) { 
    for(var i=0; i < this.length; i++) { 
        if(comparer(this[i])) return true; 
    }
    return false; 
}; 

// adds an element to the array if it does not already exist using a comparer 
// function
Array.prototype.pushIfNotExist = function(element, comparer) { 
    if (!this.inArray(comparer)) {
        this.push(element);
    }
}; 

现在使用:

var array = [{ name: "tom", text: "tasty" }];
var element = { name: "tom", text: "tasty" };
array.pushIfNotExist(element, function(e) { 
    return e.name === element.name && e.text === element.text; 
});

答案 1 :(得分:0)

尝试在Array上使用过滤器功能:

 var arr =  [ "BLABLA", "TEST", "HONORE", "SPONGEBOB", "PATRIC", "AVEA", "TEST", "HONORE", "PATRIC", "TEST"];

var res = arr.filter((item, index, array) => array.indexOf(item) === index);

res.forEach(el => console.log(el))