-1

I have an array as such:

let newArray = $('#TA2').val().split('\n');

Where #TA2 is a textarea. The output from console.log is:

["542|519", "542|519", "540|500"]

I want to show only the values that are duplicate, so the output should be: ["542|519"]

How do i do this using js/jquery? everything i try won't work unfortunately and i'm in need of help.. The diffrence in this question related to others is that i want my array to be dynamic with textarea input hence the first variable newArray that gets the values from the textarea to create a new array. The end-goal is to add a <button>, when clicked on a array should be created from the textarea and must only show the duplicate values.

SM.Mike
  • 1
  • 2

1 Answers1

0

You can use reduce and for..in. Use reduce to create a object where keys will be 542|519 like this and it's value will be the number of occurrence. So if the value is more than 1 then it is a duplicate

let dups = ["542|519", "542|519", "540|500"].reduce((acc, curr) => {
  if (acc[curr]) {
    acc[curr] += 1
  } else {
    acc[curr] = 1

  }

  return acc;
}, {});
for (let keys in dups) {
  if (dups[keys] > 1) {
    console.log(keys)
  }
}
brk
  • 48,835
  • 10
  • 56
  • 78
  • Thank you for your answer, how do I implement newArray in let dups? For instance if the textarea values changes the output should change with the new array. I hope you understand my question – SM.Mike May 15 '20 at 14:28