Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 减少重复值_Javascript - Fatal编程技术网

Javascript 减少重复值

Javascript 减少重复值,javascript,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; }, []); }; 我的问题很

我有这个:

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的值不同。我不想重复我的价值观[“BLABLA”、“TEST”“HONORE”、“海绵宝宝”、“PATRIC”、“AVEA”、“TEST”“HONORE”“PATRIC”“TEST”,还有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;
    }, []);
};

您可以扩展阵列的原型,如下所示:

// 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 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))

此行的好处可能重复:
item[self.valORname]==self.datas.valORname?!请检查此行的此方法是否仅用于选择我的项目及其item.lastname,因为我的js上的valORname=“lastname”。好的,谢谢你的回答可能的副本
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))