2

I have aan array of objects. Each object is {key, value} For each object key is an array consisting of strings ['foo', 'bar', 'baz']. I want to remove any duplicates of ['foo', 'bar', 'baz'] from the array so that further processing is only done on unique values.

Currently I'm doing this

function removeArrayDupes(input){
var i = input.length;
var previous;
input.sort();

 if (i){
        while (--i){
            var cur = input[i];
            if (!cur.key){
                // Remove empty records
                input.splice(i,1);
            } else {
                // Clear duplicates
                if ((previous) && (input[i].key) === previous){
                    input.splice(i,1);
                    regex= "/" + JSON.stringify(input[i].key) + "/g";
                    previous = input[i].key;
                } else {
                    previous = input[i].key;
                }
            }
        }
    }
}

My problem: If dupes < 3, the single duplicate is not removed.

My brain is tired because I can't see where I'm screwing this up.

I could use an extra brain or two to resolve this.

I looking for solutions usinng Vanilla JavaScript. It's not just about making it work< I want to gain comprehension on the problem and if there is a better algorith.

TIA

Sample data:

[
{key: ["foo","bar","baz"], value: "Some data"},
{key: ["foo","bar","baz"], value: "Some data"},
{key: ["foo","bar","baz"], value: "Some data"},
{key: ["baz","bar","foo"], value: "Some data"},
{key: ["bar","foo","baz"], value: "Some data"},
{key: ["bar","foo","bar"], value: "Some data"},
{key: ["bar","foo","bar"], value: "Some data"},
{key: ["bar","foo","bar"], value: "Some data"},
{key: ["bar","foo","bar"], value: "Some data"},
{key: ["baz","bar","foo"], value: "Some data"},
{key: ["baz","bar","foo"], value: "Some data"},
]

Desired output:

[
{key: ["foo","bar","baz"], value: "Some data"},
{key: ["baz","bar","foo"], value: "Some data"},
{key: ["bar","foo","baz"], value: "Some data"},
{key: ["bar","foo","bar"], value: "Some data"},
{key: ["baz","bar","foo"], value: "Some data"}
]
Ken Ingram
  • 1,538
  • 5
  • 27
  • 52

0 Answers0