获取重复的数组索引

时间:2013-08-24 10:48:42

标签: javascript arrays

在JavaScript数组中,如何获取重复字符串的索引?

示例:

MyArray = ["abc","def","abc"]; //----> return 0,2("abc");

另一个例子:

My Array = ["abc","def","abc","xyz","def","abc"] 
//----> return 0,2,5("abc") and 1,4("def");

我不知道该怎么做。 在此先感谢您的帮助!

3 个答案:

答案 0 :(得分:11)

又一种方法:

Array.prototype.getDuplicates = function () {
    var duplicates = {};
    for (var i = 0; i < this.length; i++) {
        if(duplicates.hasOwnProperty(this[i])) {
            duplicates[this[i]].push(i);
        } else if (this.lastIndexOf(this[i]) !== i) {
            duplicates[this[i]] = [i];
        }
    }

    return duplicates;
};

它返回一个对象,其中键是重复的条目,值是带有索引的数组,即

["abc","def","abc"].getDuplicates() -> { "abc": [0, 2] }

答案 1 :(得分:2)

另一种不太复杂的方法:

遍历整个数组并跟踪每个元素的索引。为此,我们需要string -> positions地图。对象是通常用于此的数据类型。键是数组的元素,值是数组中每个元素的索引/位置数组。

var map = {};

for (var i = 0; i < arr.length; i++) {
    var element = arr[i];  // arr[i] is the element in the array at position i

    // if we haven't seen the element yet, 
    // we have to create a new entry in the map
    if (!map[element]) {
        map[element] = [i];
    }
    else {
       // otherwise append to the existing array
        map[element].push(i);
    }
    // the whole if - else statement can be shortend to
    // (map[element] || (map[element] = [])).push(i)
}

现在,您可以迭代地图并删除数组值长度为1的所有条目。这些元素在数组中只出现一次:

for (var element in map) {
    if (map[element].length === 1) {
        delete map[element];
    }
}

现在map包含数组所有重复元素的string -> positions映射。例如,如果数组为["abc","def","abc","xyz","def","abc"],则map

形式的对象
var map = {
    'abc': [0,2,5],
    'def': [1,4]
};

您可以按照自己喜欢的方式进一步处理。


进一步阅读:

答案 2 :(得分:0)

    SELECT k.id_customer,k.name_customer,k.lastname_customer,r.date_bill,sum(p.price_product*us.quantity) AS TOTAL_PRICE
    FROM product p,bill r,item us,customer k
    WHERE k.id_customer=1 AND k.id_customer=r.customer_ID_customer AND us.bill_ID_bill=r.ID_bill AND p.ID_product=us.product_ID_product
    GROUP BY k.id_customer,
k.name_customer,
k.lastname_customer,
r.date_bill