Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have an array of 9 elements(maybe more).
I need to split by indexes into three arrays.
const array = [{id: 0}, {id: 1}, ..., {id: 8}];
I want to recieve 3 array like that:
const array0 = [{id: 0}, {id: 3}, {id: 6}];
const array1 = [{id: 1}, {id: 4}, {id: 7}];
const array2 = [{id: 2}, {id: 5}, {id: 8}];
You could take the remainfer of the index with three and address the dame group for every third element.
If necessary take destructuring assignment, like
[array0, array1, array2] = result;
const
array = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }, { id: 7 }, { id: 8 }],
result = array.reduce((r, o, i) => ((r[i % 3] = r[i % 3] || []).push(o), r), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can filter() the array using remainder operator %. For array1 check if the id % 3 === 0 and id % 3 === 1, id % 3 === 2 for next ones respectively
const array = Array(9).fill().map((x, i) => ({id: i}));
const array1 = array.filter(x => x.id % 3 === 0);
const array2 = array.filter(x => x.id % 3 === 1);
const array3 = array.filter(x => x.id % 3 === 2);
console.log('array1', array1)
console.log('array2', array2)
console.log('array3', array3)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How can I return the ID with the highest 'number' associated with it?
items = [
{id: 4, number: 45},
{id: 5, number: 49},
{id: 7, number: 44}
]
You can combine find and every()
const items = [
{id: 4, number: 45},
{id: 5, number: 49},
{id: 7, number: 44}
]
const res = items.find(x => items.every(a => a.number <= x.number)).id
console.log(res)
const items = [
{id: 4, number: 45},
{id: 5, number: 49},
{id: 7, number: 44}
]
const res = items.sort((a,b) => b.number - a.number)[0].id
console.log(res)
The above solution has O(n ^ 2) time complexity. If you want linear time complexity you can first find max number using Math.max and then use find
const items = [
{id: 4, number: 45},
{id: 5, number: 49},
{id: 7, number: 44}
]
const max = Math.max(...items.map(x => x.number));
const res = items.find(x => x.number === max).id;
console.log(res)
you can use reduce
const items = [
{id: 4, number: 45},
{id: 5, number: 49},
{id: 7, number: 44}
]
const max = items.reduce((max , item) => {
if(max.number < item.number){
return item;
}
return max;
});
console.log(max.id);
Both approaches require only a single loop to obtain the desired object(s).
If the data contains only one max number, then you could reduce th array and take only the one object with the greater number.
const
items = [{ id: 4, number: 45 }, { id: 5, number: 49 }, { id: 7, number: 44 }],
maxItem = items.reduce((a, b) => a.number > b.number ? a : b);
console.log(maxItem.id);
Approach for having more than one item with max number.
const
items = [{ id: 4, number: 45 }, { id: 5, number: 49 }, { id: 6, number: 49 }, { id: 7, number: 44 }],
maxItems = items.reduce((max, item, i) => {
if (!i || max[0].number < item.number) return [item];
if (max[0].number === item.number) max.push(item);
return max;
}, []);
console.log(maxItems);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Given two arrays of the same length and identical content, how can one sort an array to be the in same order as the second array, based on a shared property?
Example:
let array1 = [{id: 123, ...}, {id: 456, ...}, {id: 789, ...}] // order always stays the same
let array2 = [{id: 456, ...}, {id: 789, ...}, {id: 123, ...}] // order is always different
How can I sort array1 such that:
array1[0].id is 456 and
array2[0].id is 456
Loop through the first and push to the second by index:
let arr1 = [{id: 123}, {id: 456}, {id: 789}] // order always stays the same
let arr2 = [{id: 456}, {id: 789}, {id: 123}]
arr1.forEach((obj1, idx) => {
arr2[idx] = obj1
})
console.log(arr1, arr2)
Assuming array2 has the objects we care about and array1 specifies the order, map over the ordering array using it to select the objects to be ordered...
let array1 = [{id: 123 }, {id: 456 }, {id: 789, }]
let array2 = [{id: 456, name: '456' }, {id: 789, name: '789' }, {id: 123, name: '123' }]
let array2ElementsSortedByArray1 = array1.map(e => {
return array2.find(e2 => e2.id === e.id)
})
console.log(array2ElementsSortedByArray1)
You can create a hash of the shape {id: index, ...} from array2 and then use this to order the elements of array1. This saves you the cost of find() on each iteration.
let array1 = [{ id: 123, }, { id: 456, }, { id: 789, }] // order always stays the same
let array2 = [{ id: 456, }, { id: 789, }, { id: 123, }]
const
indeces = Object.fromEntries(array2.map(({ id }, i) => [id, i])), // { 456: 0, 789: 1, 123: 2 }
ordered = [];
array1.forEach(o => ordered[indeces[o.id]] = { ...o });
console.log(ordered)
This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Closed 2 years ago.
I am retrieving data from a football (soccer) API. The specific data I need is an array of objects (306 objects). Every object has a property called matchday with a numeric value. I want to group all the objects that share the same property and store them in an array. What I need in the end is an array of array of objects.
Example array of objects:
[
{id: 264796, matchday: 1, …},
{id: 264797, matchday: 1, …},
{id: 264798, matchday: 2, …},
{id: 264800, matchday: 2, …},
]
What I want looks like this:
[
[{id: 264796, matchday: 1, …},{id: 264797, matchday: 1, …}],
[{id: 264798, matchday: 2, …},{id: 264800, matchday: 2, …}],
]
You can use .reduce() with Object.values() to get the desired output:
const data = [
{id: 264796, matchday: 1}, {id: 264797, matchday: 1},
{id: 264798, matchday: 2}, {id: 264800, matchday: 2}
];
const result = Object.values(
data.reduce((r, c) => {
r[c.matchday] = r[c.matchday] || [];
r[c.matchday].push(c);
return r;
}, {})
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
we can use reduce
const arr = [
{id: 264796, matchday: 1},
{id: 264797, matchday: 1},
{id: 264798, matchday: 2},
{id: 264800, matchday: 2},
]
const result = arr.reduce((acc, item) => {
if (!acc.find(accSubArr => accSubArr.find(accSubArrItem => accSubArrItem.matchday === item.matchday))) {
acc.push(arr.filter(arrItem => arrItem.matchday === item.matchday))
}
return acc;
}, [])
console.log(result)
You can try this:
const data = [{
id: 264796,
matchday: 1
},
{
id: 264797,
matchday: 1
},
{
id: 264798,
matchday: 2
},
{
id: 264800,
matchday: 2
},
]
const group = data
.map(d => d.matchday)
.filter((v, i, c) => c.indexOf(v) === i)
.map(i => data.filter(d => d.matchday === i))
console.log(group)
To add to the existing answers, here's another way making use of Map with a predicate to determine the group-by value:
const groupBy = predicate => items =>
Array.from(items.reduce((agg, next) => {
const key = predicate(next);
return agg.set(key, [].concat(agg.get(key) || []).concat(next));
}, new Map()).values());
const data = [
{name: 'A', key: 1},
{name: 'B', key: 1},
{name: 'C', key: 2},
{name: 'D', key: 2},
{name: 'E', key: 3}
];
const grouped = groupBy(x => x.key)(data);
For the fun of it, here's a recursive version of groupBy:
const groupBy = predicate => function group([next, ...items], grouped = new Map()) {
if (!next) {
return Array.from(grouped.values())
}
const key = predicate(next);
return group(items, grouped.set(key, [...(grouped.get(key) || []), next]));
}
And what the heck, here's a more imperative approach to add to the mix:
const groupBy = predicate => items => {
const cache = {};
for(item of items) {
const key = predicate(item);
cache[key] = [].concat(cache[key]).concat(item).filter(x => x)
}
return Object.values(cache);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
For example, when id is equal to 1, an array is ['a', 'b'], and when id is equal to 2, another array is ['c']. The result of these two arrays is [["a","b "],["c"]]
I want the results as follows:
[["a","b"],["c"]]
my code:
var data = [{
id: 1,
name: 'a'
},
{
id: 1,
name: 'b'
},
{
id: 2,
name: 'c'
}
]
Using reduce:
var data = [{
id: 1,
name: 'a'
},
{
id: 1,
name: 'b'
},
{
id: 2,
name: 'c'
}
]
let result = data.reduce((acc, item) => {
return item.id === 1 ? acc[0].push(item.name) : acc[1].push(item.name), acc
},[[], []])
console.log(result)
I have the following two Javascript arrays:
const array1 = [{ id: 1}, { id: 2 }, { id: 3 }, { id: 4}];
const array2 = [{ id: 1}, { id: 3 }];
I now want a new array array3 that contains only the objects that aren't already in array2, so:
const array3 = [{ id: 2}, { id: 4 }];
I have tried the following but it returns all objects, and when I changed the condition to === it returns the objects of array2.
const array3 = array1.filter(entry1 => {
return array2.some(entry2 => entry1.id !== entry2.id);
});
Any idea? ES6 welcome
You could reverse the comparison (equal instead of unqual) and return the negated result of some.
const
array1 = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
array2 = [{ id: 1 }, { id: 3 }],
array3 = array1.filter(entry1 => !array2.some(entry2 => entry1.id === entry2.id));
// ^ ^^^
console.log(array3);
Nina's answer is a good start but will miss any unique elements in array 2.
This extends her answer to get the unique elements from each array and then combine them:
const
array1 = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
array2 = [{ id: 1 }, { id: 3 }, { id: 5 }],
array3 = array1.filter(entry1 => !array2.some(entry2 => entry1.id === entry2.id)),
array4 = array2.filter(entry1 => !array1.some(entry2 => entry1.id === entry2.id)),
array5 = array3.concat(array4);
console.log(array5);