jQuery using.Map to build Alphabetical array - javascript

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

Related

Ordering based on array of objects

I have to define a property sort of an array, using based an array of other objects that have 2 properties called source and target, where the source is the first element and target will be the right next.
My current array is filled in this way:
[{"id":25075,"sort":1},{"id":25076,"sort":2},{"id":25077,"sort":null}]
But based on the source target that I have it should be like this
[{"id":25075,"sort":1},{"id":25076,"sort":3},{"id":25077,"sort":2}]
For a better understanding the source target I have is it:
[{"source":25075,"target":25077},{"source":25077,"target":25076}]
Does somebody know what would be the best way to handle it?
That's is what you are looking for ?
const array = [
{ source: 25075, target: 25077 },
{ source: 25077, target: 25076 },
];
const result = array.reduce((acc, { source, target }, index) => {
if (array.length && array.length > index + 1) {
return [...acc, { id: source, sort: index + 1 }];
} else if (array.length) {
return [
...acc,
{ id: source, sort: index + 1 },
{ id: target, sort: index + 2 },
];
}
return acc;
}, []);
console.log("result", result);
At the end we will have the { id: value, sort: position } array you are looking for ?
This code doesn't handle all the cases (with duplicate or other stuff ;))
I don't really understand your problem but is that solving the issue ?
const array = [
{ id: 25075, sort: 1 },
{ id: 25076, sort: 3 },
{ id: 25077, sort: 2 },
];
const result = [];
array.sort((a, b) => (a.sort < b.sort ? -1 : 1));
array.map((v, index) => {
if (array.length > index + 1) {
result.push({ source: v.id, target: array[index + 1].id });
}
});
console.log("result", result);
Instead of the map you can also use reduce and fill an accumulator.

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 an array of objects, but the first place is fixed

Here is an example an object with an array I want to sort:
{
first: 'Zangief',
second: 'Cammy'
names: [
{name: 'Dee Jay'},
{name: 'Zangief'},
{name: 'Dhalsim'}
{name: 'Chun-Li'},
{name: 'Blanka'},
{name: 'Cammy'}
]
}
I want to have Zangief fixed on the first place and Cammy on the second place, and the rest is alphabetically ordered.
expected result:
[
{name: 'Zangief'},
{name: 'Cammy'},
{name: 'Blanka'}
{name: 'Chun-Li'},
{name: 'Dee Jay'},
{name: 'Dhalsim'},
]
I know this sorts the names alphabetically:
obj.names.sort((a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0));
and then I could find the two names and put them to the first two places, but is there a sorting function, what could do this while sorting?
You could probably just modify your function to be something like that:
obj.names.sort((a,b) => {
if (a.name === obj.first || (a.name === obj.second && b.name !== obj.first)){
return -1;
}
return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0);
});
Here's my 2 cents. I don't think it would be wise to hard code the names of the special names. I would add an order to your array that would cause the sort to override it's default ordering. So, then you wouldn't need the two properties first and second. If you are not able to modify the original array, then perhaps one of the other answers is more appropriate.
let object = {
names: [
{ name: 'Dee Jay' },
{ name: 'Zangief', order: 1 },
{ name: 'Dhalsim' },
{ name: 'Chun-Li' },
{ name: 'Blanka' },
{ name: 'Cammy', order: 2 }
]
}
object.names.sort((a, b) => {
return (a.order || Number.MAX_SAFE_INTEGER) - (b.order || Number.MAX_SAFE_INTEGER)
|| a.name.localeCompare(b.name);
});
object.names.forEach(entry => console.log(entry.name));
Another possibility, even though I don't really like it would be to pre-process the array before the new sort. Something like this:
object.names.find( entry => entry.name === 'Zangief' ).order = 1;
object.names.find( entry => entry.name === 'Cammy' ).order = 2;
object.names.sort( /* new sort */ );
with the appropriate error checking added. Again, I don't like this but it's a possibility.
You could build an object with the order of known and unkown names and take the value for ordering.
If the value is the same, then sort by string.
var object = { first: 'Zangief', second: 'Cammy', names: [{ name: 'Dee Jay' }, { name: 'Zangief' }, { name: 'Dhalsim' }, { name: 'Chun-Li' }, { name: 'Blanka' }, { name: 'Cammy' }] },
order = Object.assign(
...['first', 'second', ''].map((k, i) => ({ [object[k]]: i + 1 }))
);
object.names.sort(({ name: a }, { name: b }) =>
(order[a] || order.undefined) - (order[b] || order.undefined) || a.localeCompare(b)
);
console.log(object.names);
.as-console-wrapper { max-height: 100% !important; top: 0; }
let obj = {
first: 'Zangief',
second: 'Cammy',
names: [
{name: 'Dee Jay'},
{name: 'Zangief'},
{name: 'Dhalsim'},
{name: 'Chun-Li'},
{name: 'Blanka'},
{name: 'Cammy'}
]
};
obj.names.sort((a,b) => {
// exit early, (or trigger error if it should never happen)
if (a.name === b.name) return 0;
// No matter what, 'Zangief' gets moved to the front.
if (a.name === obj.first) return -1;
if (b.name === obj.first) return 1;
// if no Zangief, 'Cammy' always moves forward.
if (a.name === obj.second) return -1;
if (b.name === obj.second) return 1;
// otherwise, normal alphabetical sorting
return (a.name > b.name) ? 1 : -1;
});
console.log(obj.names);
Alternatively, you can do a long "one-liner":
filter returns a new array with obj.first and obj.second removed.
sort then sorts that new array in place, according to the usual rules.
concat returns a new array appending this sorted array to [obj.first, obj.second], your "starting" array.
let obj = {
first: 'Zangief',
second: 'Cammy',
names: [
{name: 'Dee Jay'},
{name: 'Zangief'},
{name: 'Dhalsim'},
{name: 'Chun-Li'},
{name: 'Blanka'},
{name: 'Cammy'}
]
};
let sorted = [{name: obj.first}, {name: obj.second}]
.concat(obj.names.filter(item => (
((item.name !== obj.first) &&
(item.name !== obj.second))
)).sort((a, b) => (a.name > b.name)
? 1
: ((b.name > a.name) ? -1 : 0)
));
console.log(sorted);
// simplified data structure
const first = 'Zangief';
const second= 'Cammy';
const names = [
'Dee Jay',
'Zangief',
'Dhalsim',
'Chun-Li',
'Blanka',
'Cammy'
];
// filter/concat (version 2) does not alter original names array.
let sorted = [first, second]
.concat(names.filter(name => (
!((name == first) || (name == second))
)).sort());
console.log("new sorted array, (version 2) via filter/concat: \n", sorted);
// orig array untouched
console.log("original names array (untouched): \n", names);
// custom sort, (version 1) alters the original names array.
names.sort((a,b) => {
// 'Zangief' gets moved to the front.
if (a === first) return -1;
if (b === first || b === second) return 1;
// Othwerwise 'Cammy' moves forward.
if (a === second) return -1;
// if (b === second) return 1;
// all other strings: normal alphabetical sorting
return (a, b) => (a > b) ? 1 : ((b > a) ? -1 : 0)
});
console.log("names array, altered, after (version 1) sorting", names);

IE Array.sort not sorting with compare function

Here is the code example which is not working properly in IE 11.
Element with id = END3 should be the last one.
Just don't tell me that I need to write sorting manually. It is not a big deal to implement it, but really?!
var list = [{
id: "SP1"
},
{
id: "SP4"
},
{
id: "END3"
},
{
id: "SP2"
}
];
console.log(
list.sort(function(a, b) {
if (a.id === "END3") {
return 1;
}
return 0;
})
);
Your sort comparison function is behaving inconsistently. The function is supposed to return < 0, 0, or > 0, not just 1 or 0. If it's not returning those values, you're giving sort the wrong information to work with, because you tell it any comparison in which a isn't the desired value is equal. It's not guaranteed that END3 will be passed as a at any point, so all comparisons will be "equal", so it's undefined what the result will be really. It's also possible that the inconsistency between SP1, END3 ("equal") and END3, SP1 ("greater") will affect the assumptions of the sorting algorithm.
var list = [{id: "SP1"}, {id: "SP4"}, {id: "END3"}, {id: "SP2"}];
console.log(list.sort(function(a, b) {
if (a.id === 'END3') {
return 1;
} else if (b.id === 'END3') {
return -1;
} else {
return 0;
}
}));
Return -1 instead of 0 in the else block. When the compare method returns 0 it leaves a and b unchanged.
var list = [{
id: "SP1"
},
{
id: "SP4"
},
{
id: "END3"
},
{
id: "SP2"
}
];
console.log(
list.sort(function(a, b) {
if (a.id === "END3") {
return 1;
}
return -1;
})
);
Docs

implement to function sorting array of objects in Angular2

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

Categories

Resources