Skip to content
Advertisement

Pushing an array into another array unless a certain value is already ‘filled’

My goal is to push an array into another array. However the array will not be pushed if the value within a[1] exists from a previous push.

simplified example of my attempt

curated_array = [];

for(i =0; i < 4; i++) {
    console.log(i);
    if(i ==0){
        a = ['John','15799','United States'];
    }
    else if(i ==1){
        a = ['Tim','86037','United States'];
    }
    else if(i==2){
        a = ['George','15799','Great Britain'];
    }
    else if(i ==3){
        a = ['Lucas','26482','Greece'];
    }
    else if(i ==4){
        a = ['Joshua','83620','United States'];
    }
    curated_array = curated_array.filter(f => f!= a).concat([a]);
}
console.log(curated_array);

Actual outcome

[ [ 'John', '15799', 'United States' ],
  [ 'Tim', '86037', 'United States' ],
  [ 'George', '15799', 'Great Britain' ],
  [ 'Lucas', '26482', 'Greece' ],
  [ 'Joshua', '83620', 'United States' ] ]

Desired outcome — to remove the row where a[1] = 15799, since it has happened already

[ [ 'John', '15799', 'United States' ],
  [ 'Tim', '86037', 'United States' ],
  [ 'Lucas', '26482', 'Greece' ],
  [ 'Joshua', '83620', 'United States' ] ]

Advertisement

Answer

While @Barmar’s comment makes your code work, it’s inefficient to iterate over the whole array every time to check if you’ve seen the value before.

Please consider using a different data structure such as a Set or key-val pairs:

Answer with key-val pairs/hash map-like:

inputs = [ [ 'John', '15799', 'United States' ],
  [ 'Tim', '86037', 'United States' ],
  [ 'George', '15799', 'Great Britain' ],
  [ 'Lucas', '26482', 'Greece' ],
  [ 'Joshua', '83620', 'United States' ] ]

// build a hash map, O(n) => you only need to build this once
uniqueInputs = {}

inputs.forEach(input => {
    valueToCheck = input[1]
    // checking for a key in an object is O(1)
    if (! (valueToCheck in uniqueInputs) ) 
        uniqueInputs[ valueToCheck ] = input 
}) 

// turn the object back into an array
output = Object.values( uniqueInputs )

Output:

[
    [
        "John",
        "15799",
        "United States"
    ],
    [
        "Lucas",
        "26482",
        "Greece"
    ],
    [
        "Joshua",
        "83620",
        "United States"
    ],
    [
        "Tim",
        "86037",
        "United States"
    ]
]
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement