Sort an array containing objects based on another array

Possible duplicate:
JavaScript - Sort an array based on another array of integers
Javascript - sort an array based on another array

If I have an array like this:

['one','four','two'] 

And one more such array:

 [{ key: 'one' },{ key: 'two' },{ key: 'four' }] 

How do I sort the second array so that its key property follows the order of the first? In this case, I want:

 [{ key: 'one' },{ key: 'four' },{ key: 'two' }] 
+4
source share
2 answers

Here is my example:

 function orderArray(array_with_order, array_to_order) { var ordered_array = [], len = array_to_order.length, len_copy = len, index, current; for (; len--;) { current = array_to_order[len]; index = array_with_order.indexOf(current.key); ordered_array[index] = current; } //change the array Array.prototype.splice.apply(array_to_order, [0, len_copy].concat(ordered_array)); } 

Implementation Example:

 var array_with_order = ['one', 'four', 'two'], array_to_order = [ {key: 'one'}, {key: 'two'}, {key: 'four'} ]; orderArray(array_with_order, array_to_order); console.log(array_to_order); //logs [{key: 'one'}, {key: 'four'}, {key: 'two'}]; 

Ordinary fiddle: http://jsfiddle.net/joplomacedo/haqFH/

+2
source

We can use the sort () function to do this by passing it a user-defined function that performs the comparison. This function should return 3 possible values โ€‹โ€‹indicated by a or b for comparison:

return -1 if a indexed below b

return 0 if a is considered equal to b

return 1 if a indexed more than b

With this in mind, we can define a function such as:

 function sortFunction(a,b){ var indexA = arr.indexOf(a['key']); var indexB = arr.indexOf(b['key']); if(indexA < indexB) { return -1; }else if(indexA > indexB) { return 1; }else{ return 0; } } 

This function will take the objects you define in your array and find where that value is in the arr array, which is the array you are comparing with. Then it compares the index and returns values โ€‹โ€‹as needed.

We use this function by passing the function to the sort() function as such:

testArray.sort(sortFunction)

where testArray is the array you are trying to sort.

You can look here where I made this example, and you can see that the second object in your array is โ€œwarnedโ€ to you, before and after the sort function is called. http://jsfiddle.net/Sqys7/

+5
source

Source: https://habr.com/ru/post/1447804/


All Articles