JavaScript - Sort Array Based on Another Array

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));

Sort an array of objects based on another array of ids

Ramda really shines for these types of problems.

Where the size of the data is small, we can use a simple reduce function, and indexOf helper.

// match id of object to required index and insert
var sortInsert = function (acc, cur) {
var toIdx = R.indexOf(cur.id, a);
acc[toIdx] = cur;
return acc;
};

// point-free sort function created
var sort = R.reduce(sortInsert, []);

// execute it now, or later as required
sort(b);
// [ { id: 2 }, { id: 3 }, { id: 1 }, { id: 4 } ]

This works well for small(ish) data sets but the indexOf operation on every iteration through the reduction is inefficient for large data sets.

We can remedy this by tackling the problem from the other side, lets use groupBy to group our objects by their id, thus creating a dictionary lookup (much better!). We can then simply map over the required indexes and transform them to their corresponding object at that position.

And here is the solution using this approach:

var groupById = R.groupBy(R.prop('id'), b);

var sort = R.map(function (id) {
return groupById[id][0];
});

sort(a);
// [ { id: 2 }, { id: 3 }, { id: 1 }, { id: 4 } ]

Finally, this is yet another solution, which is very succinct:

R.sortBy(R.pipe(R.prop('id'), R.indexOf(R.__, a)))(b);
// [ { id: 2 }, { id: 3 }, { id: 1 }, { id: 4 } ]

I love the way you can compose functions with behaviour and separate the algorithm from the data upon which it acts using Ramda. You end up with very readable, and easy to maintain code.

Sort Array of Objects based on position of value in another Array of Strings

You can loop the correct_order array and filter the unsorted array by using the js filter function. If filter match push to an new array.

const UNSORTED = [{Type: 'Grass', Value: 'Wet'}, {Type: 'Sand', Value: 'Dry'}, {Type: 'Animal', Value: 'Dog'}];

const CORRECT_ORDER = ['Animal','Plant','Sand','Grass'];

let sorted = []
CORRECT_ORDER.forEach(k => {
let n = UNSORTED.filter(obj => {
return obj.Type === k
})
if (n.length > 0) {
sorted.push(n);
}

})

console.log(sorted);

Javascript sort array of objects based on another array

that ?

const arr1 = 
[ { id: 21, name: 'Joey', vehicle: 'car' }
, { id: 6, name: 'Kevin', vehicle: 'car' }
, { id: 10, name: 'Luis', vehicle: 'van' }
]

const arr2 =
[ { id: 6, name: 'Kevin' }
, { id: 21, name: 'Joey' }
, { id: 10, name: 'Luis' }
]


// Arr1 ordered..
const arr1_ord = arr2.map(a2=> arr1.find(x=>x.id===a2.id))

console.log( arr1_ord )
.as-console-wrapper {max-height: 100%!important;top:0}

Sort an array based on another array

You can do it using the map function on the second array where you find the element matching the number

Example

const questions = [
{
id: 1,
data: {
question: "What is your name?"
}
},
{
id: 2,
data: {
question: "How old are you?"
}
},
{
id: 3,
data: {
question: "Where do you leave?"
}
},
{
id: 4,
data: {
question: "Foo"
}
},
{
id: 5,
data: {
question: "Bar"
}
},
]

const newOrder = [2,1,5,4,3]

const newQuestionsOrdered = newOrder.map(x => questions.find(question => question.id === x))

console.log(newQuestionsOrdered)

Sort array object based on another array in javascript

You need to use sort method on the array. And then compare the index of field on the order array.

const data = [
{
uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
field: "6283cb3ca573a56e11587c46",
value: 'test val 6'
},
{
uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
field: "627f816d8443318c6aaa1220",
value: ''
}
]

const order = [ '6283cb3ca573a56e11587c46', '627f816d8443318c6aaa1220' ];

data.sort((a,b) => order.indexOf(a.field) - order.indexOf(b.field));
console.log(data);

JS how to sort() one array based on another array’s sortation

Create a two-dimensional working array, whose elements are pairs of values from arrA and arrB:

var work = [];
arrA.forEach(function( v, i ) {
work[ i ] = [ arrA[i], arrB[i] ];
});

Now you can arrange work in any order, and the values from arrA and arrB will stay in lockstep:

work.sort(function(x, y) {
return Math.sign( x[0], y[0] );
});

(In the above example, we are ordering by the element in slot 0, which is from arrA. To order by the elements in arrB, change 0 to 1.)

Now you can alter work, e.g.:

work.reverse();

And extract the corresponding elements that were originally from arrA:

let newAarrA = work.map(function(x) {
return x[0]; // from arrA
});
console.log(newArrA);

(Change 0 to 1 to get the corresponding elements from arrB instead.)

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)

C# sorting part of an array based on another array

Im sure there are alot of ways to do this, I have alot of LINQ left to learn but the following should get you started;

// First, get the users that are mentioned by a PinnedItem 
var pinnedUsers = pinnedItems.Select(x => users.FirstOrDefault(y => y.UserId == x.UserId));
// Get all the users that are not mentioned in a PinnedItem
var unpinnedUsers = users.Except(pinnedUsers);
// Combine both
var both = pinnedUsers.Concat(unpinnedUsers);


Related Topics



Leave a reply



Submit