Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - Remove duplicates in array of arrays based on the lenght of string on 1st position. JS

I have an array of arrays like this:

arr = 
[
  [0 ,  abc  ],
  [7 ,  def  ],
  [10,  ghi  ],
  [0 , abcjkl]
]

What I want is to find duplicates based on the value on 0th position (in my example: [0, abc], [0, abcjkl]) and remove the array with shorter string on 1st postiton. The result should look like this:

[
  [7 ,  def  ],
  [10,  ghi  ],
  [0 , abcjkl]
]

Thank you for any help.

EDIT:

I have working algorithm just doesnt seem like the best approach.

function findDupes(arr) {
  let dupe = null;
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (arr[i] !== arr[j]) {
        if (arr[i][1] === arr[j][1]) {
          if (arr[i][0].length >= arr[j][0].length) {
            dupe = arr[j];
          } else {
            dupe = arr[i];
          }
        }
      }
    }
  }
  return dupe;
}

let check = findDupes(arr);
while (check) {
    filteredValues.splice(arr.indexOf(check), 1);
    check = findDupes(arr);
}
question from:https://stackoverflow.com/questions/65920650/remove-duplicates-in-array-of-arrays-based-on-the-lenght-of-string-on-1st-positi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use hash map to solve this.Loop through each inner array and put elements in hash Map like let hashMap = {0:'abc',10:'ghi'}.

If the key already exists in hash Map, check the if the value's length is smaller than new value, if so, replace.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...