JS sort by predefined string values [duplicate] - javascript

This question already has answers here:
Javascript - sort array based on another array
(26 answers)
Sorting an Array of JavaScript Objects a Specific Order (using existing function)
(6 answers)
Closed 2 years ago.
I have an array of items that I want to sort based on the category property:
const arr = [{
id: 1,
category: 'bar'
}, {
id: 4,
category: 'baz'
},
{
id: 5,
category: 'foo'
}]
What I want is to sort it based on the following order:
- foo
- bar
- baz
How can I do it with an array comparator?
arr.sort(function(a, b) {
return ?
})
Do I need to give each category an order number and do a.order - b.order? Or there is another clever way to do it?

You can put your order into an array and use indexOf within sort.
const arr = [{
id: 1,
category: 'bar'
}, {
id: 4,
category: 'baz'
},
{
id: 5,
category: 'foo'
}]
const order = ["foo","bar","baz"]
arr.sort( (a,b) => order.indexOf(a.category) - order.indexOf(b.category) )
console.log(arr)

Related

filter array of objects by the value of one key if this key is also included in an array of strings [duplicate]

This question already has answers here:
How to filter object array using an array in JS? [duplicate]
(4 answers)
Filter array of objects based on another array in javascript
(10 answers)
Remove all elements contained in another array [duplicate]
(17 answers)
Closed 1 year ago.
how do you filter out objects from an array of objects by the value of one key if this key is also included in an array of strings?
const objArr = [
{
identifiers: {id: 1, name: "X"},
char: {char1: a, char2: b}
},
{
identifiers: {id: 2, name: "Y"},
char: {char1: c, char2: d}
},
]
not filter out all objcts that have a name that is included in this arr:
with strArr = [
"X", "Z"
]
result:
const objArrAfterFilter = [
{
identifiers: {id: 2, name: "Y"},
char: {char1: c, char2: d}
},
]
This should do the trick:
const objArr = [{
identifiers: {id: 1, name: "X"},
char: {char1: 'a', char2: 'b'}
},
{
identifiers: {id: 2, name: "Y"},
char: {char1: 'c', char2: 'd'}
},
];
strArr = ["X", "Z"]
filtered_array = objArr.filter((element)=>{
return !strArr.includes(element.identifiers.name);
});
console.log(filtered_array)
Basically, just use the filter method in the array prototype, which returns a new list elements in objArr that satisfy the condition in the function.
The condition we're specifying is that the name of the identifier of the element should not be included within strArr, so the condition looks like this:
!strArr.includes(element.identifiers.name)

Return values from array1 that are not in array2 [duplicate]

This question already has answers here:
Filter Array Not in Another Array
(3 answers)
Closed 2 years ago.
arr1 = [
{
empID: 1,
empName: 'Sam'
},
{
empID: 2,
empName: 'Robert'
},
{
empID: 3,
empName: 'Josh'
},
{
empID: 4,
empName: 'Kane'
}
];
arr2 = [2, 3]
I want to return only empID from arr1, which are not present in arr2, i.e. 1 & 4. I am not able to use find() and filter() appropriately.
Thanks for the help.
You can use filter and includes.
const employees = arr1.filter(emp => !arr2.includes(emp.empID));

Select only specific properties from an array of objects [duplicate]

This question already has answers here:
Extract certain properties from all objects in array
(5 answers)
Closed 4 months ago.
Let's say I create object like this:
updates.push({
id: this.ids[i],
point: point,
value: value
});
Later on I want to use JSON.stringify on updates object, however I need only
point and value like:
updates[{point: 1, value: 12}, {point: 2, value: 24}]
What's the best ES6 solution for that?
I looked at some examples with delete, but that's not what I actually need, as I do not want to delete ids.
Try the following :
JSON.stringify(updates.map(({point,value})=>({point,value})));
let updates = [{id : 1, point : 1, value: 2},{id : 1, point : 1, value: 2}];
console.log(JSON.stringify(updates.map(({point,value})=>({point,value}))));
If updates is an array. Then you might want something like this:
const newArrayWithoutId = updates.map(({ point, value }) => {
return {
point,
value,
}
}
Just ({id, ...rest}) => ({...rest}) is too short for an answer, so how about this?
const withoutId = ({id, ...rest}) => ({...rest})
const vals = [
{id: 'a', point: 1, value: 'foo'},
{id: 'b', point: 2, value: 'bar'},
{id: 'c', point: 3, value: 'baz', meaning: 42}
]
const reduced = vals.map(withoutId)
console.log(reduced)

Split object into two properties [duplicate]

This question already has answers here:
Convert object to array of key–value objects like `{ name: "Apple", value: "0.6" }`
(3 answers)
Closed 1 year ago.
a very beginner question below I'm sure, apologies for asking but I've had a good hunt on the matter with no luck... I'm looking to 'break' or 'expand' the following:
var words = { hello: 2, there: 3, heres: 1, text: 1 }
Into this:
var words = [{
word: 'hello',
count: 2
}, {
word: 'there',
count: 3
}, {
word: 'heres',
count: 1
}, {
word: 'text',
count: 1
}]
I've been messing around a lot with Underscore.js, but must be missing something very obvious. Any help will be greatly appreciated, thanks!
You can do this with Object.keys() and map().
var words = { hello: 2, there: 3, heres: 1, text: 1 }
var result = Object.keys(words).map(e => ({word: e, count: words[e]}))
console.log(result)
You can also first create array and then use for...in loop to push objects.
var words = { hello: 2, there: 3, heres: 1, text: 1 }, result = [];
for(var i in words) result.push({word: i, count: words[i]})
console.log(result)
Possible solution using Array#map.
const words = { hello: 2, there: 3, heres: 1, text: 1 },
res = Object.keys(words).map(v => ({ word: v, count: words[v] }));
console.log(res);
Or Array#reduce.
const words = { hello: 2, there: 3, heres: 1, text: 1 },
res = Object.keys(words).reduce((s,a) => (s.push({ word: a, count: words[a] }), s), []);
console.log(res);
Here's a solution using underscore's map function:
words = _.map(words, (v, k) => ({word: k, count: v}));
Underscore's map can iterate over an object. The first parameter to the iteratee is the value and the second parameter is the key.
let object = {
"06.10 15:00": 3.035,
"06.10 21:00": 3.001,
};
let arr = [];
for (const [key, value] of Object.entries(object)) {
arr.push({ date: key, value: value });
}
console.log(arr);

Filter the original array of objects by array of ids

I have two arrays:
array a:
var a = [
{
id: 1,
name: 'a'
},
{
id: 2,
name: 'b'
},
{
id: 3,
name: 'c'
}
];
array ids:
var ids = [1];
I want to array a filtered by array ids, result i wanted:
var a = [
{
id: 1,
name: 'a'
}
];
The most important thing is i want the change on the original array, rather than return a new array.
underscore solution is better:)
You can use .filter
a = a.filter(function(el){
return ~ids.indexOf(el.id)
});
// should give you [{id: 1, name: 'a'}]
Today I tried to solve similar task (filtering the original array of objects without creating a new array) and this is what I came up with:
const a = [{ id: 1, name: 'a'}, { id: 2, name: 'b'}, { id: 3, name: 'c'}];
const ids = [1];
Array.from(Array(a.length).keys()).reverse().forEach(index =>
!ids.some(id => id === a[index].id) && a.splice(index, 1)
);
console.log(a); // [{ id: 1, name: 'a'}]
The point is that we need to loop back through the original array to be able to use Array.prototype.splice, but I didn't want the for-loop, I wanted to have ES6 one-liner. And Array.from(Array(a.length).keys()).reverse() gives me a list of reversed indexes of the original array. Then I want to splice the original array by current index only if the corresponding item's id is not present in the ids array.

Categories

Resources