0

I have a 2D array like this one in JavaScript:

result=[["user1", "java"], ["user2", "python"],["user1", "java"], ["user1", "C++"], ["user1", "java"], ["user2", "Python"]....]  

you can see that ["user1", "java"] comes 3 times and ["user2", "python"] 2 times.

I want to clean this array so that every couple of element must appear only once.it means that if "user1" can appear again, it should be with another language but not with "java". can some one help me?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
  • maybe this ? https://stackoverflow.com/questions/44014799/javascript-how-to-remove-duplicate-arrays-inside-array-of-arrays – cmgchess Jul 03 '22 at 07:52

3 Answers3

0

You could try this one:

let result= [
  ["user1", "java"], 
  ["user2", "python"],
  ["user1", "java"], 
  ["user1", "C++"], 
  ["user1", "java"], 
  ["user2", "Python"]
];
const map = new Object();
result.forEach((item) => {
  if(!map[item[0]]){
    map[item[0]] = new Array();
  }
  const user = map[item[0]];
  const language = (item[1] || '').toLowerCase().trim();
  if(user.indexOf(language) < 0){
    user.push(language);
  }
});
result = new Array();
Object.keys(map).forEach((user) => {
  map[user].forEach((language) => {
    result.push([user,language]);
  });  
});
console.log(result);
Matus
  • 1
  • 1
0

You can create a Set out of the array by joining the user and language strings, which would remove the duplicates. And then simply split the strings back to get the desired array.

const 
  result = [["user1", "java"], ["user2", "python"], ["user1", "java"], ["user1", "c++"], ["user1", "java"], ["user2", "python"]],
  uniques = Array.from(new Set(result.map((res) => res.join("-")))).map(
    (data) => data.split("-")
  );

console.log(uniques);

Relevant Documentations:

SSM
  • 2,855
  • 1
  • 3
  • 10
0

You can do this with a single loop over the array using reduce, join and Set as:

const result = [
    ['user1', 'java'],
    ['user2', 'python'],
    ['user1', 'java'],
    ['user1', 'C++'],
    ['user1', 'java'],
    ['user2', 'python'],
];

const [uniqueElements] = result.reduce((acc, curr) => {
        const [uniq, set] = acc;
        if (!set.has(curr.join(','))) {
            set.add(curr.join(','));
            uniq.push(curr);
        }
        return acc;
    },
    [[], new Set()],
);

console.log(uniqueElements);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
DecPK
  • 24,537
  • 6
  • 26
  • 42