implement to function sorting array of objects in Angular2 - javascript

I am using Angular2, I would like to sort array of objects based on properties in the object. I need to paginate those objects because of limitation of space. So, I do not want to use Pipe in the context of NgFor. I just would like to implement a sorting function before it rendered into DOM. If someone has some information, could you give some guide? All I found was using PipeTransform. So, I am asking you.

You can use underscorejs _.sortBy method.
Code example:
_.sortBy(arr, function(o) { return o.start.dateTime; })

try array.sort() of JS
Example arr.sort()
var fruit = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']
Example arr.sort(compareFunction)
var items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Zeros', value: 37 }
];
// sort by value
items.sort(function (a, b) {
return a.value - b.value;
});
// sort by name
items.sort(function(a, b) {
var nameA = a.name.toUpperCase(); // ignore upper and lowercase
var nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});

Related

Sort by Capacity and Name in ReactJS using array sort()

I have one question. How can I sort array items first by their capacity and then by the first letter of their name? The main idea is first to be sorted by capacity from low to high or high to low and then if two items have the same capacity, those two items to be sorted by the first letter of their name.
Here is a basic code sample from me
myArray.sort((eventA, eventB) => {
if (this.state.sort.highToLow.enabled) {
return eventA.capacity > eventB.capacity ? -1 : 1;
} else if (this.state.sort.lowToHigh.enabled) {
return eventA.capacity > eventB.capacity ? 1 : -1;
} else { return 0; }
})
you can use lodash sortBy method
_.sortBy(myArray, ['capacity', 'name']);
try some thing like this. sort method, check for name when capacity is same.
const data = [
{
name: "z",
capacity: 2,
},
{
name: "b",
capacity: 1,
},
{
name: "a",
capacity: 1,
},
];
data.sort((a, b) => {
if (a.capacity === b.capacity) {
return a.name > b.name ? 1 : -1;
}
return a.capacity - b.capacity;
});
console.log(data);

Sort out array of object using its value [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 2 years ago.
I have an array of objects:
array = [
{
name: 'fever',
possibility: '20%',
},
{
name: 'hiv',
possibility: '25%',
},
{
name: 'heart-attack',
possibility: '20%'
},
{
name: 'covid',
possibility: '40%',
},
]
I want to sort out the array of objects using its possibility. The object with higher possibility will be on top and if two or many objects have the same possibility then it will be sorted alphabetically. How can I do that?
Use String.localeCompare() with the numeric option to sort using possibility, but use - (minus) to get descending results. If the comparison returns 0 (equals), use localeCompare again to compare the names:
const array = [{"name":"fever","possibility":"20%"},{"name":"hiv","possibility":"25%"},{"name":"heart-attack","possibility":"20%"},{"name":"covid","possibility":"40%"}]
const result = array.sort((a, b) =>
-a.possibility.localeCompare(b.possibility, undefined, { numeric: true })
||
a.name.localeCompare(b.name)
)
console.log(result)
Maybe not only for this, but you could consider using the library Lodash.
It has a lot of cool features, such as sortBy that does exactly what you need.
_.sortBy(array, ['possibility']);
An additional note, is usually be better to store the possibility field (or any percentage value) with a number from 0 to 1, or at least from 1 to 100 as a number, and then adding the % char when displaying :)
To directly answer your questions, this works:
array.sort((e1, e2) => e1.possibility > e2.possibility ? 1 : -1)
Feel free to swap -1 and 1 to move from ascending to descending.
Try like this:
var array = [
{
name: 'fever',
possibility: '20',
},
{
name: 'hiv',
possibility: '25',
},
{
name: 'heart-attack',
possibility: '20'
},
{
name: 'covid',
possibility: '40',
},
]
function sortArray() {
return array.sort((a, b)=> b.possibility- a.possibility)
}
console.log(sortArray());
Prints:
[{
name: "covid",
possibility: "40"
}, {
name: "hiv",
possibility: "25"
}, {
name: "fever",
possibility: "20"
}, {
name: "heart-attack",
possibility: "20"
}]
Based on answer from here:
How to sort 2 dimensional array by column value?
Pure javascript solution would be :
array.sort((a,b) => a.possibility < b.possibility ? 1 : -1)
which would result in :
0: {name: "covid", possibility: "40%"}
1: {name: "hiv", possibility: "25%"}
2: {name: "heart-attack", possibility: "20%"}
3: {name: "fever", possibility: "20%"}
const array = [
{
name: 'fever',
possibility: '20%',
},
{
name: 'hiv',
possibility: '25%',
},
{
name: 'heart-attack',
possibility: '20%'
},
{
name: 'covid',
possibility: '40%',
},
];
const sorted = array.sort((a, b) => {
if (a.possibility > b.possibility) {
return 1;
}
if (a.possibility < b.possibility) {
return -1;
}
return 0;
});
console.log(sorted);
I've added another array entry just to double test the alphabetical ordering as a backup. Run the snippet and check the result:
let array = [
{
name: 'heart-attack',
possibility: '20%',
},
{
name: 'hiv',
possibility: '25%',
},
{
name: 'fever',
possibility: '20%'
},
{
name: 'covid',
possibility: '40%',
},
{
name: 'aaa',
possibility: '40%',
},
]
function compare( a, b ) {
newA = Number(a.possibility.slice(0, -1))
newB = Number(b.possibility.slice(0, -1))
if ( newA < newB ){
return -1;
} else if ( newA > newB ){
return 1;
} else if ( newA === newB && a.name < b.name){
return -1;
} else if ( newA === newB && a.name > b.name){
return 1;
}
return 0;
}
const sortedArr = array.sort(compare)
console.log( sortedArr )

Find (and remove) duplicates in array of objects depending on object attributes

I want to remove duplicates in an array of objects, depending on object attributes.
Simplified example:
Assuming you have an array like:
[
{
name: 'alice',
something: 123
},
{
name: 'alice',
something: 321
},
{
name: 'bob',
something: 213
}
]
I want to remove objects, wich have the same value for name, but I want to decide which object to remove with some custom calculation (e.g. keep the object with bigger value for something).
I was able to adapt the accepted answer in find duplicate values in a JavaScript array, but that does not work so well with more than 2 duplicates.
You can try with reduce and object, set properties base on your condition.
Then convert it to array by Object.values.
var arr = [
{
name: 'alice',
something: 123
},
{
name: 'alice',
something: 321
},
{
name: 'bob',
something: 213
}
];
var res = arr.reduce( (acc,b) => {
if ((acc[b.name] && acc[b.name].something < b.something) || !acc[b.name]) {
acc[b.name] = b;
}
return acc;
}, {});
var newArr = Object.values(res);
console.log(newArr);
You could use a hash table as reference to the same name objects.
var array = [{ name: 'alice',something: 123 }, { name: 'alice', something: 321 }, { name: 'bob', something: 213 }],
result = array.reduce(function (hash) {
return function (r, a) {
if (!(a.name in hash)) {
hash[a.name] = r.push(a) - 1;
return r;
}
if (r[hash[a.name]].something < a.something) {
r[hash[a.name]] = a;
}
return r;
};
}(Object.create(null)), []);
console.log(result)

jQuery using.Map to build Alphabetical array

Hey Im doing something like this:
temp = $.map(response, function(item) {
return {
label: item.name,
value: item.id
};
});
temp.unshift({label: "", value: 0});temp
Is there a way to make sure the return is built in alphabetical order?
You can always sort the response prior to creating the map or simply sort the resulting mapped array.
var response = [{ name: 'z', id: 1 }, { name: 'a', id: 2 }];
response = response.sort(function (a, b) {
return a.name < b.name? -1 : +(a.name > b.name);
});
response[0].name; //a
Please note that +(a.name > b.name) is used to explicitely return 0 when equal and 1 when greater, since that's what the sort function expects.
temp.sort(function(a, b) {
return a.value > b.value ? 1 : -1;
});
var result = temp.map(function(e){
return list[e.index]
});

Create array of keys by sorting values

I have an object that looks like this
myList: {
id1:{
ts:'2010-01-12T00:51:00',
name:"roger"
},
id2:{
ts:'2011-01-12T05:22:00',
name: "Tom"
},
id3:{
ts:'2013-01-12T11:32:00',
name:"Jack"
}
}
I know objects cant be sorted so i wanted to know how i can generate an array of just the keys,which are sorted according to the key "ts". I want this in descending order.
So the array for the above object will be [id3,id2,id1]
once i have this array i can make operations like this where arr is sorted array and myList is the object
for(var i=0:i<arr.length;i++)
{
alert(myList[arr[i]].name);
}
var keys = Object.keys(myList).sort(function(a, b) {
if (myList[a].ts == myList[b].ts) {
return 0;
}
return myList[a].ts < myList[b].ts ? 1 : -1;
});
console.log(keys);
jsfiddle: http://jsfiddle.net/pWq2L/
Explanation:
First you export keys from the object: Object.keys(myList)
You sort using custom comparison function and in it you refer to the .ts attribute of the compared values. a and b are the keys of the compared elements
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Given this data structure, and assuming there is a good reason for it to not be an array:
var myList = {
id1: {
ts: new Date('2010-01-12T00:51:00'),
name: 'Roger'
},
id2: {
ts: new Date('2011-01-12T05:22:00'),
name: 'Tom'
},
id3:{
ts: new Date('2013-01-12T11:32:00'),
name: 'Jack'
}
}
We can create and sort an array like so:
var arr = [];
Object.keys(myList).forEach(function(item) {
arr.push(myList[item]);
});
arr.sort(function(a, b) {
return a.ts > b.ts ? -1 : a.ts < b.ts ? 1 : 0;
})
One way to extend zerkms solution is to work with an object augmented with smart properties. The versatile reduce comes in handy:
var result = keys.reduce(function(arr, k, i) {
var item = {
key: k,
index: i,
value: myList[k]
};
arr.push(item);
return arr;
}, []);
//result:
[
{ index:0 , key: id3, value: {...} },
{ index:1 , key: id2, value: {...} },
{ index:2 , key: id1, value: {...} }
]
reduce is part of the ECMAScript 5th edition; so you may fill in some gap with a polyfill.
http://jsfiddle.net/pWq2L/3/

Categories

Resources