1

I have multidimensional array with strings:

const arr = [['a', 'b'], ['c', 'd'], ['d', 'a']]

How can i log to console all values that occur in all nested arrays more than 1 time? (For this example function should console.log 'a' and 'd').

Thanks for the help

2
  • You can create a set and add them, check if exists, console.log them. I can create a fiddle if you need Commented Feb 12, 2019 at 14:34
  • Looks like a dupe question, looking... Commented Feb 12, 2019 at 14:35

5 Answers 5

4

You first flat the arr.Then remove duplicates from it using Set. And loop through it then compare lastIndexOf and indexOf

const arr = [['a', 'b'], ['c', 'd'], ['d', 'a']]
let flat = arr.toString().split(',');
[... new Set(flat)].forEach(a => {
  if(flat.indexOf(a) !== flat.lastIndexOf(a)) console.log(a)
})

Sign up to request clarification or add additional context in comments.

Comments

3

let findDupesInMDArray = (arr) => {
  // flatten the array
  const flat = arr.flat();
  // filter for dupes
  return flat.filter((item, index) => flat.indexOf(item) != index)
}

let array = [['a', 'b'], ['c', 'd'], ['d', 'a']]
const dupes = findDupesInMDArray(array)
console.log(dupes)

Comments

1

Using spread syntax, Array#flat, Array#reduce, Array#filter and Array#map.

const arr = [['a', 'b'], ['c', 'd'], ['d', 'a']]

const res = Array.from(arr.flat().reduce((a,c)=>{
  return a.set(c, (a.get(c)||0) + 1);
}, new Map()))
.filter(([,c])=> c > 1)
.map(([k])=>k);

console.log(res);

Comments

0

You could count the items by using a Map and get only the items with a count greater than one.

const 
    count = (m, a) => Array.isArray(a) ? a.reduce(count, m) : m.set(a, (m.get(a) || 0) + 1);

var array = [['a', 'b'], ['c', 'd'], ['d', 'a']],
    result = Array
        .from(array.reduce(count, new Map), ([k, v]) => v > 1 && k)
        .filter(Boolean)
    
console.log(result);

Comments

0

Here's a more basic approach:

var array = [['a', 'b'], ['c', 'd'], ['d', 'a']]
  var result = [];
  for (var i in array){
   for (var l in array[i]){
    if(array[i][l]==='a'||array[i][l]==='d')
      result.push(array[i][l])
}}

var unique = new Set(result) //creates a set with unique values
console.log(unique) //should log the set {'a','d'}

What we're doing here is

  1. looping through the nested arrays twice
  2. pushing the elements (if the element === 'a' or element ==='d') into a new array called result.
  3. creating a new set with the unique values only

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.