Sort an Array by keys based on another Array?
Just use array_merge
or array_replace
. array_merge
works by starting with the array you give it (in the proper order) and overwriting/adding the keys with data from your actual array:
$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';
$properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer);
// or
$properOrderedArray = array_replace(array_flip(array('name', 'dob', 'address')), $customer);
// $properOrderedArray: array(
// 'name' => 'Tim',
// 'dob' => '12/08/1986',
// 'address' => '123 fake st',
// 'dontSortMe' => 'this value doesnt need to be sorted')
PS: I'm answering this 'stale' question, because I think all the loops given as previous answers are overkill.
Sort array elements based on another array's keys
How about this? Using array_replace()
:
<?php
$arr1 = array('0' => 'John', '1' => 'George', '2' => 'James', '3' => 'Harry');
$arr2 = array('0' => '12', '1' => '8', '2' => '34', '3' => '23');
arsort($arr2);
var_dump(array_replace($arr2, $arr1)); // array(4) { [2]=> string(5) "James" [3]=> string(5) "Harry" [0]=> string(4) "John" [1]=> string(6) "George" }
Demo
Javascript - sort array based on another array
One-Line answer.
itemsArray.sort(function(a, b){
return sortingArr.indexOf(a) - sortingArr.indexOf(b);
});
Or even shorter:
itemsArray.sort((a, b) => sortingArr.indexOf(a) - sortingArr.indexOf(b));
PHP - Sort array with another array
$ordered_fruits = array();
foreach($order as $value) {
if(array_key_exists($value,$fruits)) {
$ordered_fruits[$value] = $fruits[$value];
}
}
Sort object array based on another array of keys
Try this
var a = ['d','a','b','c'] ;var b = [{a:1},{c:3},{d:4},{b:2}];
b.sort(function(x,y){ var xkey = a.indexOf(Object.keys(x)[0]); var ykey = a.indexOf(Object.keys(y)[0]); return xkey - ykey;})
document.body.innerHTML += JSON.stringify(b,0,4);
Sort array of objects based on another array of objects key
You can try this, it finds the first elem in array2
matching the name, in order, from the array1
.. removes it from array2
and then adds it to the sortedArray2
.
const array1 = [
{
"name": "B",
"order": 1
},
{
"name": "C",
"order": 2
},
{
"name": "D",
"order": 3
},
{
"name": "B",
"order": 4
},
{
"name": "A",
"order": 5
}
]
const array2 = [
{
"name": "B",
"order": 1,
"id": 3638
},
{
"name": "B",
"order": 1,
"id": 3661
},
{
"name": "C",
"order": 2,
"id": 3658
},
{
"name": "D",
"order": 3,
"id": 3659
},
{
"name": "A",
"order": 5,
"id": 3636
}
]
const sortedArray2 = []
for(const item of array1) {
sortedArray2.push(
array2.splice(
array2.findIndex(elem => elem.name === item.name), 1
)
)
}
console.log(sortedArray2)
Sort array of objects based on another array and move items not in that array to the end
I'd start by building a complete array
to perform the sort, including missing elements from the keys, in their original order...
var arrayObject = [{key: 'g'},{key: 'a'},{key: 'b'},{key: 'c'},{key: 'd'},{key: 'e'}];
var array = ['a', 'c', 'd', 'e'];
arrayObject.forEach(o => { if (!array.includes(o.key)) array.push(o.key)})
// now your code works fine let result = arrayObject.sort((a, b) => { return array.indexOf(a.key) - array.indexOf(b.key); });
console.log(result)
Related Topics
Convert PHP Array to JavaScript
PHP - Concatenate or Directly Insert Variables in String
Able to See a Variable in Print_R()'S Output, But Not Sure How to Access It in Code
Compiling an Ast Back to Source Code
Strtotime() Doesn't Work With Dd/Mm/Yyyy Format
Convert a Series of Parent-Child Relationships into a Hierarchical Tree
Replace Urls in Text With HTML Links
Is There a PHP Function That Can Escape Regex Patterns Before They Are Applied
Calculate Number of Hours Between 2 Dates in PHP
Sending Email With PHP from an Smtp Server
PHP Function to Generate V4 Uuid
What Are the PHP Operators "" and ":" Called and What Do They Do
Many-To-Many Relationships Examples
Highlight the Difference Between Two Strings in PHP
How to Access PHP Variables in JavaScript or Jquery Rather Than ≪PHP Echo $Variable ≫