D
D
Dmitry Samutin2018-09-11 15:11:59
JavaScript
Dmitry Samutin, 2018-09-11 15:11:59

What algorithm would you recommend for finding the difference between two arrays?

Good day.
There was a need to create a function in JS, which:

  • receives at the input: two arrays (1st original, 2nd modified)
  • at the output: the ordinal number of a different element and the type of difference
  • input arrays in turn consist of an array with two elements
  • types of difference:
    1. 1 element added (always to the end of the array)
    2. 1 element removed
    3. 1 element changed

What is available:
function func(a,b){
  // Если старый массив короче значит добавлен 1 элемент в конец массива
  if (b.length > a.length) {
    return {num: b.length - 1, type: 'add'};
  }
  
  // Если старый массив длинее значит удалён 1 элемент
  else if (b.length < a.length) {
    for (let i = 0; i < a.length; i++) {
      if (a[i][0] != b[i][0] || a[i][1] != b[i][1]) {
        return {num: i, type: 'delete'};
      }
    }
    
  // Иначе был изменён элемент
  } else {
    for (let i = 0; i < a.length; i++) {
      if (a[i][0] != b[i][0] || a[i][1] != b[i][1]) {
        return {num: i, type: 'change'};
      }
    }
  }
}

Does anyone know a better algorithm?
I will be very grateful.
JsFiddle:

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2018-09-11
@samutin

Levenshtein distance

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question