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?

1

3 Answers 3

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; }

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

1 Comment

Thanks a lot! it is working just the way I was expecting
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);

Comments

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:

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.