6

I need to go through multiple arrays and create one new array with all the values from the multiple arrays without duplicate, is there any plugins/quick way I can do this?

var x = {
  "12": [3, 4],
  "13": [3],
  "14": [1, 4]
};

The result should look something like this:

[1,3,4];
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
Adam
  • 2,418
  • 3
  • 17
  • 22
  • Please use the snippet editor to create a [mcve] that shows your effort and code – mplungjan Jan 26 '18 at 15:23
  • 1
    Possible duplicate of [How to get the difference between two arrays in Javascript?](https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript) – Heretic Monkey Jan 26 '18 at 15:23
  • `[...new Set([].concat.apply([], Object.values(x)))]` – Seraf Jan 26 '18 at 15:32

5 Answers5

3

You can do this using ES6 spread syntax and Object.values method.

var x = {
  "12": [3, 4],
  "13": [3],
  "14": [1, 4]
}

const result = [...new Set([].concat(...Object.values(x)))]
console.log(result)

Solution using Lodash

var x = {
  "12": [3, 4],
  "13": [3],
  "14": [1, 4]
}

const result = _.uniq(_.flatten(_.values(x)))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

You can use array#from with set and array#reduce.

var x = {"12": [3, 4],"13": [3],"14": [1, 4]};
    result = Array.from(new Set(Object.values(x).reduce((r,a) => r.concat(a), [])));
console.log(result)

You can also get all values from your object and create an object and get all the keys from it.

var x = {"12": [3, 4],"13": [3],"14": [1, 4]};
    result = Object.keys(Object
                        .values(x)
                        .reduce((r,a) => (a.forEach(v => r[v] = true), r),{})
                        ).map(Number);
console.log(result)
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

You can loop over all your keys and then your arrays:

var outputArray = [];
for (var y in x) {
    for (var z = 0; z < x[y].length; z++) {
        if (outputArray.indexOf(x[y][z]) === -1) {
            outputArray.push(x[y][z]);
        }
    }
}

https://jsfiddle.net/80c8ctuo/

Mathew Berg
  • 28,625
  • 11
  • 69
  • 90
0

You can get all the arrays using Object.values and then merge them into one array using concat. Following this you can use filter to remove duplicates.

const x = {"12": [3, 4],"13": [3],"14": [1, 4]};
const result = [].concat.apply([], Object.values(x)).filter((el, i, a) => i === a.indexOf(el));
console.log(result)
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
0

If by any chance the object is from JSON.parse :

var j = '{ "12": [3, 4], "13": [3], "14": [1, 4] }'

var a = [], x = JSON.parse(j, (k, v) => (a[v] = +v, v))

console.log( a.filter(isFinite) )
Slai
  • 22,144
  • 5
  • 45
  • 53