JS ES6: Find Different Values between Two Arrays and Get Its Indices

In this post, you will find out how to find different values between two arrays by getting the different values from the second array, and get the indices/keys of them, in JavaScript. In my case, this function is useful when I want to update the sort order of a list.

For example, I have a list with sort order [1, 2, 3, 4, 5, ...]. When I move item 3 to the top, the list should be updated to [3, 1, 2, 4, 5, ...]. You can see the sort orders that gets updated are item 3, 1, and 2, the rests remain unchanged. So, I need to find that updated sort orders and its indices on the updated list. Maybe I can just pass all of the sort orders after they gets updated to the sort order updater function on the server-side, but I bet it will consume quite a long time if my list contains a very long amount of data. That’s why I just need the changed sort orders only.

Example

I will use the same example as what I wrote above. Here I have two arrays, the first array arrA contains the initial items before I update the sort orders. The next arrB contains items after they get reordered, which, in this example, I move the item 3 to the top, and it moves down the position of item 1 and 2.

const
  arrA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  arrB = [3, 1, 2, 4, 5, 6, 7, 8, 9, 10];

 

Solution

Here I wrote the function that does the job. The short, vanilla, ES6 way to do this, is written in Code 2.

const f = (a, b) => Object.assign(...b.map((v, i) => a[i] !== v ? { [i]: v } : {}));

Then, if we use the function on the arrays, it will output something like this:

Fig 1. The result of the function
Fig 1. The result of the function

Explanation

If you can’t read the short version of the code clearly, here is the full-readable one for you, that you can read in Fig 2.

Fig 2. The full-readable version of the function
Fig 2. The full-readable version of the function

First block of code filters different values with index and returns them as array of index-value pair objects: [{index: val}, {index: val}, ...]. Equal value will be assigned as empty object {}. So, if the input arguments are a: [10, 20, 30], b: [10, 30, 20], then the output of this code block is [{}, {1: 30}, {2: 20}].

The next block of code spreads the array (by spread syntax ...) and build the object as a list of index-value pairs. This action includes filtering empty objects {} so they will be excluded from the output. If we take the result from the first code block ([{}, {1: 30}, {2: 20}]) as the input for this process, then the function will output {1: 30, 2: 20}, and that’s the final output of the complete function.

Conclusion

Based on the knowledge of array and object operation on JavaScript especially ES6, we have figured out how to find different values between two arrays and get its indices.


Thanks for reading this article, and I hope you find this useful! 👍