Javascript remove duplicates from multidimensional array

I have a two-dimensional array:

[[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]]

Is there any smart way to remove duplicated elements from this? It should return such array:

[[7,3], [3,8], [1,2]]

Thanks!

OBezzad

1051 silver badge7 bronze badges

asked Dec 2, 2013 at 22:49

3

arr = [[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]];

function multiDimensionalUnique[arr] {
    var uniques = [];
    var itemsFound = {};
    for[var i = 0, l = arr.length; i < l; i++] {
        var stringified = JSON.stringify[arr[i]];
        if[itemsFound[stringified]] { continue; }
        uniques.push[arr[i]];
        itemsFound[stringified] = true;
    }
    return uniques;
}

multiDimensionalUnique[arr];

Explaination:

Like you had mentioned, the other question only dealt with single dimension arrays.. which you can find via indexOf. That makes it easy. Multidimensional arrays are not so easy, as indexOf doesn't work with finding arrays inside.

The most straightforward way that I could think of was to serialize the array value, and store whether or not it had already been found. It may be faster to do something like stringified = arr[i][0]+":"+arr[i][1], but then you limit yourself to only two keys.

answered Dec 2, 2013 at 23:07

0

This requires JavaScript 1.7:

var arr = [[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]];

arr.map[JSON.stringify].filter[[e,i,a] => i === a.indexOf[e]].map[JSON.parse]
// [[7,3], [3,8], [1,2]]

Credit goes to jsN00b for shortest version.

answered Dec 2, 2013 at 23:14

MattMatt

19.4k1 gold badge54 silver badges68 bronze badges

2

var origin = [[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]];

function arrayEqual[a, b] {
    if [a.length !== b.length] { return false; }
    for [var i = 0; i < a.length; ++i] {
        if [a[i] !== b[i]] {
            return false;
        }
    }
    return true;
}

function contains[array, item] {
    for [var i = 0; i < array.length; ++i] {
        if [arrayEqual[array[i], item]] {
            return true;
        }
    }
    return false;
}

function normalize[array] {
    var result = [];
    for [var i = 0; i < array.length; ++i] {
        if [!contains[result, array[i]]] {
            result.push[array[i]];
        }
    }
    return result;
}

var result = normalize[origin];
console.log[result];

//jsfiddle.net/2UQH6/

answered Dec 2, 2013 at 23:11

qiu-deqingqiu-deqing

1,3137 silver badges13 bronze badges

Hi folks.

This is a quick guide demonstrating different ways of removing identical elements from an array. It is very easy to follow but unfortunately Medium does not provide the capability of copy and paste the code so you have to type yourself. The based array that is used in this example consists of only primitive values which we’re using in everyday coding.

This is the nasty, 16 elements array on which all the examples are based:

const basedArray = [1, 2, 1, 55, ‘cat’, 23, 55, 1 , 7, true, ‘cat’, ‘dog’, ‘1’, 1, true, false]

1. forEach

ForEach method loops through all the elements of the ‘basedArray’ and can perform an operation on each of these elements. In this case, we have to check whether each of the based array’s item occurs in the freshly created ‘shorterArray’. If not, each of them will be send there, filling up the ‘shorterArray’ with the values from the ‘basedArray’. Every duplicated item will be ignored because it’s already in the new array.

forEach

RESULT:

Console logging of the ‘shorterArray’ results in a new array with unique values.

console.log — forEach result

2. Set

Set is a new object type that allows of collection on unique values. Our based array is delivered to the Set class as a parameter, where the duplicated values are removed. Results are expanded using the spread operator […] and everything is placed inside square brackets as a new array. All that in one line of code :]

new Set[]

RESULT:

console.log — Set result

3. Map array

Let’s declare a new variable outside of the map loop and assign it to an empty array [afterMappingArray]. Map functions scans all the elements in the based array. Using a conditional statement we’re checking whether they have appeared in the ‘afterMappingArray’ at least once. If not, they will be pushed to the new, array. If they are already there they will be ignored.

map

RESULT:

console.log — map result

4. Filter

Filter loop creates a new array and returns an expression after each of its iteration, that is evaluated to either true or false. Using ‘indexOf’, we’re checking whether the index of each element is equal to the first found index of element of this array. In other words, only firstly discover items will meet the condition [evaluate to true] and will be assigned to the returned array.

Everything is assigned a the new variable because the filter function creates a new array.

RESULT:

console.log —filter result

5. Reduce

Reduce method is used to reduce an array to the single value. Very often used to add numbers and retrieve their sum. We’re using it’s two parameters here to do the job: ‘accumulator’ and ‘nextItem’. ‘Accumulator’ is initialised as an empty array[[]]on the end of the callback function and after each iteration goes back to the accumulator and check whether this new array contains each of the items from the based array. If it’s true then it returns only the accumulator, if it’s false it returns the accumulator, which is expanded to a new array using spreading operator […], and adds the ‘nextItem’ to the new array.

Everything is assigned to a new variable.

RESULT:

console.log —reduce result

6. For … of

For … of, similarly to forEach presented in this article, loops though all values of the ‘basedArray’ pushing unique elements to the freshly declared ‘targetArray’, which is outside of the loop. The algorithm checks the occurrence of each elements in the ‘targetArray’. If it cannot find it, places this element in the new array [targetArray].

for …of

RESULT:

console.log — for … of result

Bonus — removing duplicates from multidimensional array

The two-dimensional array, expands all the elements of its children into a single array using the spread syntax […] and the concat[] method. The spreaded elements are concatenated to an empty array using just one line of code.

removing duplicates from multidimensional array

Having all elements inside one array we can filter through its elements, searching and removing duplicates. The rest creates a new array of unique items.

RESULT:

removing duplicates from multidimensional array — result

Hope that was helpful to someone :]

Thanks for reading!

How to remove duplicate in 2d array JavaScript?

“how to remove duplicates in two dimensional array javascript\” Code Answer.
array1 = array1. filter[function[val] {.
return array2. indexOf[val] == -1;.
// Or, with the availability of ES6:.
array1 = array1. filter[val => ! array2. includes[val]];.

How do you remove duplicates from an array of arrays?

To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.

Does JavaScript have multidimensional arrays?

Javascript has no inbuilt support for multidimensional arrays, however the language is flexible enough that you can emulate this behaviour easily by populating your arrays with separate arrays, creating a multi-level structure.

What is multidimensional array in JavaScript?

A multidimensional array is an array that contains another array. For example, // multidimensional array const data = [[1, 2, 3], [1, 3, 4], [4, 5, 6]];

Chủ Đề