I have an array. I need to group this array by groups and sort by position. I tied to create a new array with group names as keys and values as sorted array grouped by group, but didn't work well. How can I do this?
a = [
{id:1,name:'qw'group:'C',name:'hite',position:'1'},
{id:2,name:'qwe'group:'B',name:'ite',position:'2'},
{id:3,name:'qwer'group:'A',name:'ite',position:'3'},
{id:4,name:'qer'group:'D',name:'te',position:'4'},
{id:5,name:'wer'group:'C',name:'whit',position:'5'},
{id:6,name:'er'group:'B',name:'whi',position:'6'},
]
function groupDo(array){
var groups = [];
for (var i in array){
groups[array[i].group] = array[i].group;
}
for (var i in array){
if (groups[array[i].group] == array[i].group){
groups[array[i].group] = array[i];
}
}
}
Here's a simple straight forward answer:
var sortByPosition = function(obj1, obj2) {
return obj1.position - obj2.position;
};
var arr = [
{ id: 1, name: 'qw', group: 'C', name: 'hite', position: '1' },
{ id: 2, name: 'qwe', group: 'B', name: 'ite', position: '2' },
{ id: 3, name: 'qwer', group: 'A', name: 'ite', position: '3' },
{ id: 4, name: 'qer', group: 'D', name: 'te', position: '4' },
{ id: 5, name: 'wer', group: 'C', name: 'whit', position: '5' },
{ id: 6, name: 'er', group: 'B', name: 'whi', position: '6' },
];
var grouped = {};
for (var i = 0; i < arr.length; i += 1) {
if(!grouped[arr[i].group]) {
grouped[arr[i].group] = [];
}
grouped[arr[i].group].push(arr[i]);
}
for (var group in grouped) {
grouped[group] = grouped[group].sort(sortByPosition);
}
console.log(grouped);
When you want to do stuff like this though, it's usually recommended to use a utility library like lodash or underscore.js, so that you don't have to "reinvent the wheel". Here's how it would look like using one of these libraries:
var arr = [
{ id: 1, name: 'qw', group: 'C', name: 'hite', position: '1' },
{ id: 2, name: 'qwe', group: 'B', name: 'ite', position: '2' },
{ id: 3, name: 'qwer', group: 'A', name: 'ite', position: '3' },
{ id: 4, name: 'qer', group: 'D', name: 'te', position: '4' },
{ id: 5, name: 'wer', group: 'C', name: 'whit', position: '5' },
{ id: 6, name: 'er', group: 'B', name: 'whi', position: '6' },
];
var grouped = _.groupBy(arr, 'group');
for (var group in grouped) {
_.sortBy(grouped[group], 'position');
}
console.log(grouped);
Here ya go!
a = [
{id:1,name:'qw',group:'C',name:'hite',position:'1'},
{id:2,name:'qwe',group:'B',name:'ite',position:'2'},
{id:3,name:'qwer',group:'A',name:'ite',position:'3'},
{id:4,name:'qer',group:'D',name:'te',position:'4'},
{id:5,name:'wer',group:'C',name:'whit',position:'5'},
{id:6,name:'er',group:'B',name:'whi',position:'6'},
]
function groupAndSort(array, groupField, sortField) {
var groups = {}; // This object will end being keyed by groups, and elements will be arrays of the rows within the given array, which have been sorted by the sortField
// Put all the rows into groups
for (var i = 0; i < array.length; i++) {
var row = array[i];
var groupValue = row[groupField];
groups[groupValue] = groups[groupValue] || [];
groups[groupValue].push(row);
}
// Sort each group
for (var groupValue in groups) {
groups[groupValue] = groups[groupValue].sort(function(a, b) {
return a[sortField] - b[sortField];
});
}
// Return the results
return groups;
}
var groupedAndSorted = groupAndSort(a, "group", "position");
If you want to group objects, first think about what the resulting data would look like. Maybe something like this?
var grouped = {
A : [
{id:3,name:'qwer', group:'A',name:'ite',position:'3'}
],
B : [],
C : [],
D : []
};
And so on. To transform a list into an object, consider using .reduce().
.reduce() takes a function as its first argument, and a resulting object as the second. The function iterates through each element of the array and reduces it into the given object.
var data = [
{id:1,name:'qw', group:'C',name:'hite',position:'1'},
{id:2,name:'qwe', group:'B',name:'ite',position:'2'},
{id:3,name:'qwer', group:'A',name:'ite',position:'3'},
{id:4,name:'qer', group:'D',name:'te',position:'4'},
{id:5,name:'wer', group:'C',name:'whit',position:'5'},
{id:6,name:'er', group:'B',name:'whi',position:'6'},
]
// acc is the accumulated object, x is each element of the array
data.reduce(function(acc, x) {
// first check if the given group is in the object
acc[x.group] = acc[x.group] ? acc[x.group].concat(x) : [x];
return acc;
}, {}); // this is the resulting object
Now all you need to do is use the built in sort to order the resulting arrays. You could do this by iterating through the keys of the resulting object and applying .sort() to each array. .sort() takes a function as an argument which accesses the data and provides a comparison function.
// a and b are elements of the array
array.sort(function(a, b) {
if (a.position > b.position) {
return -1;
} else if (b.position > a.position) {
return 1;
} else {
return 0;
}
});
And you would implement it like so
var result = Object.keys(data).map(function(d){
return d.sort(f); // f is the function above
});
Related
This question already has answers here:
How do I sort an array of objects based on the ordering of another array?
(9 answers)
Javascript - sort array based on another array
(26 answers)
Closed 4 years ago.
I have two arrays.
itemsArray =
[
{ id: 8, name: 'o'},
{ id: 7, name: 'g'},
{ id: 6, name: 'a'},
{ id: 5, name: 'k'},
{ id: 4, name: 'c'}
]
sortArray = [4,5]
How can i sort itemsArray by sortArray (lodash or pure), but i want to for this:
newArray =
[
{ id: 4, name: 'c'},
{ id: 5, name: 'k'},
{ id: 8, name: 'o'},
{ id: 7, name: 'g'},
{ id: 6, name: 'a'}
]
In a case like this where you want to sort on multiple levels, you need to sort them in descending order of importance inside your sorting function.
In this case we sort regularly on cases where both elements are either in or not in the sorting array.
var itemsArray = [
{ id: 8, name: 'o' },
{ id: 7, name: 'g' },
{ id: 6, name: 'a' },
{ id: 5, name: 'k' },
{ id: 4, name: 'c' }
];
var sortArray = [4, 5];
var sortedItemsArray = itemsArray.sort(function (a, b) {
if (sortArray.includes(a.id) == sortArray.includes(b.id)) { //both or neither are in sort array
return b.id - a.id;
}
else if (sortArray.includes(a.id)) { //only a in sort array
return -1;
}
else { //only b in sort array
return 1;
}
});
console.log(sortedItemsArray);
The above snippet could be expanded in multiple ways, but a popular approach is to separate it into several sorting steps.
var itemsArray = [
{ id: 8, name: 'o' },
{ id: 7, name: 'g' },
{ id: 6, name: 'a' },
{ id: 5, name: 'k' },
{ id: 4, name: 'c' }
];
var sortArray = [4, 5];
function sortId(a, b) {
return b.id - a.id;
}
function sortIdByList(a, b) {
if (sortArray.includes(a.id)) {
return -1;
}
if (sortArray.includes(b.id)) {
return 1;
}
return 0;
}
//TEST
var sortedItemsArray = itemsArray
.sort(sortId)
.sort(sortIdByList);
console.log(sortedItemsArray);
This pattern can be easier to maintain as each step is clearly labeled and the functions can be reused in other sorting cases.
The only downside to this pattern is that you end up iterating over the list multiple times, thus increasing the time to sort. Usually this is a non-issue but on very large lists this can be significant.
Sort by array index only
As the comments points out i misread the question, so my previous two sorting snippets doesn't necessarily give the desired result.
This version sorts only by id index in the sorting array:
var itemsArray = [
{ id: 8, name: 'o' },
{ id: 7, name: 'g' },
{ id: 6, name: 'a' },
{ id: 5, name: 'k' },
{ id: 4, name: 'c' }
];
var sortArray = [4, 5];
//TEST
var sortedItemsArray = itemsArray
.sort(function (a, b) {
//Calculate index value of a
var A = sortArray.indexOf(a.id);
if (A == -1) {
A = sortArray.length;
}
//Calculate index value of b
var B = sortArray.indexOf(b.id);
if (B == -1) {
B = sortArray.length;
}
//Return comparison
return A - B;
});
console.log(sortedItemsArray);
You could take the indices of the array for keeping the relative position and take the special items with a negative index to top for sorting.
Then sort the array by taking the indices.
var array = [{ id: 8, name: 'o' }, { id: 7, name: 'g' }, { id: 6, name: 'a' }, { id: 5, name: 'k' }, { id: 4, name: 'c' }],
sortArray = [4, 5],
indices = array.reduce((r, { id }, i) => (r[id] = i, r), {});
sortArray.forEach((id, i, { length }) => indices[id] = i - length);
array.sort(({ id: a }, { id: b }) => indices[a] - indices[b]);
console.log(array);
console.log(indices);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Trying to parse one data set that has a bunch of the same "secondaryIDs" in way that i can group and iterate through them together.
In english what im trying to do is
"select a unique group of all items where the value of field is unique "
'use strict';
const data = [{
Group: 'A',
Name: 'SD'
}, {
Group: 'B',
Name: 'FI'
}, {
Group: 'A',
Name: 'MM'
}, {
Group: 'B',
Name: 'CO'
}];
let unique = [...new Set(data.map(item => item.Group))];
console.log(unique);
Which gives ["A"],["B"]
but what im looking for is
{
A: [ "SD","MM" ],
B: [ "FI","CO" ],
}
For this, I would use array.reduce instead of array.map because what you're actually hoping to return is a new value, not a modified array, the reduce method is perfect when you want to literally reduce the array into a single output value, in your case an object of unique groups. Maybe try something like this:
let unique = data.reduce((acc, { Group, Name }) => {
if (!(acc.hasOwnProperty(Group))) {
acc[Group] = [Name];
} else {
acc[Group].push(Name);
};
return acc;
}, {});
I've also added a pen for this at: https://codepen.io/anon/pen/BGpgdz?editors=1011 so you can see this working.
Hope this helps!
You can also reduce your array to the grouped object (keyed by Group values):
const data = [{
Group: 'A',
Name: 'SD'
}, {
Group: 'B',
Name: 'FI'
}, {
Group: 'A',
Name: 'MM'
}, {
Group: 'B',
Name: 'CO'
}];
const grouped = data.reduce((a, {Group, Name}) => {
if (!(Group in a)) a[Group] = [Name];
else a[Group].push(Name);
return a;
}, {});
console.log(grouped);
can do something like..
const map = {};
data.forEach( d => {
if( map[d.Group] ) {
map[d.Group].push(d.Name);
} else {
map[d.Group] = [d.Name];
}
})
console.log(map)
I think the easiest way to achieve this would be to use Array.prototype.reduce method to create an object that maps unique Group names to arrays that contain Names. You can supply an empty object literal as your initial reduce accumulator:
const data = [{
Group: 'A',
Name: 'SD'
}, {
Group: 'B',
Name: 'FI'
}, {
Group: 'A',
Name: 'MM'
}, {
Group: 'B',
Name: 'CO'
}];
var namesByGroup = data.reduce((map, el) => {
map[el.Group] ? map[el.Group].push(el.Name) : map[el.Group] = [el.Name];
return map;
}, {});
console.log(namesByGroup);
If you're interested in a functional approach, here is a solution using Ramda:
const group =
R.pipe(
R.groupBy(R.prop('Group')),
R.map(R.map(R.prop('Name'))));
console.log(
group([
{Group: 'A', Name: 'SD'},
{Group: 'B', Name: 'FI'},
{Group: 'A', Name: 'MM'},
{Group: 'B', Name: 'CO'}])
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
can also be done using forEach
const data = [{
Group: 'A',
Name: 'SD'
}, {
Group: 'B',
Name: 'FI'
}, {
Group: 'A',
Name: 'MM'
}, {
Group: 'B',
Name: 'CO'
}];
const somefunction = (data) => {
let arr = {}
data.forEach( ({Group, Name}) => {
Group in arr ? arr[Group].push(Name) : arr[Group] = [Name]
})
return arr;
}
console.log(somefunction(data))
I have array of objects called newArray and oldArray.
Like this : [{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]}]
example :
newArray = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4]}
]
oldArray = [
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4,5]}
]
result will be = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4]},
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]}
];
I wanted to merge both the array in such a way that whenever name and label are equal in both the arrays it should only consider newArray value.
I have tried
function mergeArrayWithLatestData (newData, oldData) {
let arr = [];
let i = 0; let j =0
while ((i < newData.length) && (j < oldData.length)) {
if ((findIndex(newData, { name: oldData[i].name, label: oldData[i].label })) !== -1) {
arr.push(newData[i])
} else {
arr.push(newData[i]);
arr.push(oldData[i]);
}
i += 1;
j += 1;
}
while (i < newData.length) {
arr.push(newData[i]);
}
return arr;
}
But i am not getting correct result.
Any suggestions?
You could add all array with a check if name/label pairs have been inserted before with a Set.
var newArray = [{ name: 'abc', label: 'abclabel', values: [1, 2, 3, 4, 5] }, { name: 'test', label: 'testlabel', values: [1, 2, 3, 4] }],
oldArray = [{ name: 'oldArray', label: 'oldArrayLabel', values: [1, 2, 3, 4, 5] }, { name: 'test', label: 'testlabel', values: [1, 2, 3, 4, 5] }],
result = [newArray, oldArray].reduce((s => (r, a) => {
a.forEach(o => {
var key = [o.name, o.label].join('|');
if (!s.has(key)) {
r.push(o);
s.add(key);
}
});
return r;
})(new Set), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can simply use Array.reduce() to create a map of the old Array and group by combination of name and label. Than iterate over all the elements or objects of the new Array and check if the map contains an entry with given key(combination of name and label), if it contains than simply update it values with the values of new array object, else add it to the map. Object.values() on the map will give you the desired result.
let newArray = [ {name: 'abc', label: 'abclabel', values: [1,2,3,4,5]}, {name: 'test', label: 'testlabel', values: [1,2,3,4]} ];
let oldArray = [ {name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]}, {name: 'test', label: 'testlabel', values: [1,2,3,4,5]} ];
let map = oldArray.reduce((a,curr)=>{
a[curr.name +"_" + curr.label] = curr;
return a;
},{});
newArray.forEach((o)=> {
if(map[o.name +"_" + o.label])
map[o.name +"_" + o.label].values = o.values;
else
map[o.name +"_" + o.label] = o;
});
console.log(Object.values(map));
In your first while loop
while ((i < newData.length) && (j < oldData.length)) {
if ((findIndex(newData, { name: oldData[i].name, label: oldData[i].label })) !== -1)
{
arr.push(newData[i])
} else {
arr.push(newData[i]);
arr.push(oldData[i]);
}
i += 1;
j += 1;
}
i and j always have the same value, you are only comparing entries at the same positions in the arrays. If they have different lengths, you stop comparing after the shorter array ends. Your second while-loop will only be executed if newArray is larger than oldArray.
One possible solution is to copy the oldArray, then iterate over newArray and check if the same value exists.
function mergeArrayWithLatestData (newData, oldData) {
let arr = oldData;
for(let i = 0; i < newData.length; i++) {
let exists = false;
for(let j = 0; j < oldData.length; j++) {
if(newData[i].name === oldData[j].name && newData[i].label === oldData[j].label) {
exists = true;
arr[j] = newData[i];
}
}
if(!exists) {
arr.push(newData[i]);
}
}
return arr;
}
var newArray = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4]}
]
var oldArray = [
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4,5]}
]
console.log(mergeArrayWithLatestData(newArray, oldArray));
You make copies of the original arrays, and in the first one, or change the element, or add:
function mergeArrayWithLatestData (a1, a2) {
var out = JSON.parse(JSON.stringify(a1))
var a2copy = JSON.parse(JSON.stringify(a2))
a2copy.forEach(function(ae) {
var i = out.findIndex(function(e) {
return ae.name === e.name && ae.label === e.label
})
if (i!== -1) {
out[i] = ae
} else {
out.push(ae)
}
})
return out
}
[ https://jsfiddle.net/yps8uvf3/ ]
This is Using a classic filter() and comparing the name/label storing the different pairs using just +. Using destructuring assignment we merge the two arrays keeping the newest first, so when we check the different the newest is always the remaining.
var newArray = [{ name: "abc", label: "abclabel", values: [1, 2, 3, 4, 5] },{ name: "test", label: "testlabel", values: [1, 2, 3, 4] }];
var oldArray = [{ name: "oldArray", label: "oldArrayLabel", values: [1, 2, 3, 4, 5] },{ name: "test", label: "testlabel", values: [1, 2, 3, 4, 5] }];
var diff = [];
oldArray = [...newArray, ...oldArray].filter(e => {
if (diff.indexOf(e.name + e.label) == -1) {
diff.push(e.name + e.label);
return true;
} else {
return false; //<--already exist in new Array (the newest)
}
});
console.log(oldArray);
Create an object, with key as name and label. Now, first add all the oldData records to the object and then add newData records in object. If there are any objects in common with same name and label, it will overwrite the old Data value. Finally, get the values of the Object which is the merged data set.
var arr1 = [{name: 'def', label: 'abclabel', values: [6,7]}, {name: 'abc', label: 'abclabel', values: [1,2,3,4,5]}];
var arr2 = [{name: 'xy', label: 'abclabel', values: [6,7]}, {name: 'abc', label: 'abclabel', values: [6,7]}];
function mergeArrayWithLatestData(newData, oldData) {
var result = {};
[...oldData, ...newData].forEach(o => result[o.name + "~~$$^^" + o.label] = o);
return Object.values(result);
}
let result = mergeArrayWithLatestData(arr1, arr2);
console.log(result);
Alternative: using a Map as the initial value in a reducer. You should know that (as in the selected answer) you loose information here, because you're not comparing on the values property within the array elements. So one of the objects with name/label pair test/testlabel will be lost in the merged Array. If concatenation in the snippet was the other way around (so newArray.concat(oldArray), the test/testLabel Object within the merged Array would contain another values property value.
const newArray = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4]}
];
const oldArray = [
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4,5]}
];
const merged = [
...oldArray.concat(newArray)
.reduce( (map, value) =>
map.set(`${value.name}${value.label}`, value),
new Map())
.values()
];
console.log(merged);
function mergeArray(newArray, oldArray) {
var tempArray = newArray;
oldArray.forEach(oldData => {
var isExist = tempArray.findIndex(function (newData) {
return oldData.name === newData.name;
});
if (isExist == -1) {
tempArray.push(oldData);
}
});
return tempArray;
}
var newArray = [{
name: 'abc',
label: 'abclabel',
values: [1, 2, 3, 4, 5]
}, {
name: 'test',
label: 'testlabel',
values: [1, 2, 3, 4]
}];
var oldArray = [{
name: 'oldArray',
label: 'oldArrayLabel',
values: [1, 2, 3, 4, 5]
}, {
name: 'test',
label: 'testlabel',
values: [1, 2, 3, 4, 5]
}];
var resultArray = [];
resultArray = mergeArray(newArray, oldArray);
console.log(resultArray);
I have an object like this:
var database = [
{
category: 'CPUs',
id: 1,
products: [Product, Product, Product] //Product is an object
},
{
category: 'GPUs',
id: 2,
products: [Product, Product]
}
];
and so on..
I'd like to get 10 random products in total, non-repeating. There can be more than one from the same category, as long as they are different products. How can I do this? I tried this:
function getRandomFromObject(){
var productsCollected = [];
while(productsCollected.length < 10){
var randomCategory = database[Math.floor(Math.random()*database.length)];
var randomProduct = randomCategory.products[Math.floor(Math.random()*randomCategory.products.length)];
productsCollected.push(randomProduct);
}
return productsCollected;
}
Things become easier if you first concatenate all the products into one array, then shuffle that array and finally take the first 10 from that:
function shuffle(a) {
for (let i = a.length; i; i--) {
let j = Math.floor(Math.random() * i);
[a[i - 1], a[j]] = [a[j], a[i - 1]];
}
return a;
}
function getRandomFromObject(count){
return shuffle([].concat(...database.map(o => o.products))).slice(0, count);
}
var database = [
{
category: 'CPUs',
id: 1,
products: ['a', 'b', 'c'] //Product is an object
},
{
category: 'GPUs',
id: 2,
products: ['d', 'e']
},
{
category: 'GPUs',
id: 3,
products: ['f', 'g', 'h', 'i', 'j']
}
];
console.log(getRandomFromObject(10).join(','));
Addendum: If you can have the same Product object occurring in different categories, then apply a Set to the concatenated array, so to eliminate these duplicates:
return shuffle([...new Set([].concat(...database.map(o => o.products)))]).slice(0, count);
ES5 Code
As you asked in comments for ES5, and the need to consider products with the same ISBN property as the same products, here is the code for that:
function shuffle(a) {
for (var i = a.length; i; i--) {
var j = Math.floor(Math.random() * i);
var temp = a[i - 1];
a[i - 1] = a[j];
a[j] = temp;
}
return a;
}
function getRandomFromObject(count){
var uniq = {}; // Unique list of products, keyed by ISBN
database.forEach(function (o) {
o.products.forEach(function (product) {
uniq[product.isbn] = product;
});
});
var products = [];
for (product in uniq) {
products.push(uniq[product]);
}
return shuffle(products).slice(0, count);
}
var database = [
{
category: 'CPUs',
id: 1,
products: [{ isbn: 'a' }, { isbn: 'b' }, { isbn: 'c' }] //Product is an object
},
{
category: 'GPUs',
id: 2,
products: [{ isbn: 'd' }, { isbn: 'a' }, { isbn: 'j' }] // has same isbn as in CPUs
},
{
category: 'Others',
id: 3,
products: [{ isbn: 'e' }, { isbn: 'f' }, { isbn: 'g' }, { isbn: 'h' }, { isbn: 'i' }]
}
];
console.log(getRandomFromObject(10));
I have an array object:
[
{ id:1, name: 'Pedro'},
{ id:2, name: 'Miko'},
{ id:3, name: 'Bear'},
{ id:4, name: 'Teddy'},
{ id:5, name: 'Mouse'}
]
And I have an array with ids [1, 3, 5],
How can I filter the array object to leave records only with id's from the second one?
If Array.includes() is supported, you can use it with Array.filter() to get the items:
const array = [
{ id: 1, name: 'Pedro'},
{ id: 2, name: 'Miko'},
{ id: 3, name: 'Bear'},
{ id: 4, name: 'Teddy'},
{ id: 5, name: 'Mouse'}
];
const filterArray = [1,3,5];
const result = array.filter(({ id }) => filterArray.includes(id));
console.log(result);
If includes is not supported, you can use Array.indexOf() instead:
var array = [
{ id: 1, name: 'Pedro'},
{ id: 2, name: 'Miko'},
{ id: 3, name: 'Bear'},
{ id: 4, name: 'Teddy'},
{ id: 5, name: 'Mouse'}
];
var filterArray = [1,3,5];
var result = array.filter(function(item) {
return filterArray.indexOf(item.id) !== -1;
});
console.log(result);
Maybe take a Array.prototype.reduce in combination with an Array.prototype.some. This keeps the order of the given array need.
var data = [
{ id: 3, name: 'Bear' },
{ id: 4, name: 'Teddy' },
{ id: 5, name: 'Mouse' },
{ id: 1, name: 'Pedro' },
{ id: 2, name: 'Miko' },
],
need = [1, 3, 5],
filtered = need.reduce(function (r, a) {
data.some(function (el) {
return a === el.id && r.push(el);
});
return r;
}, []);
document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');
To keep the order of data you can use Array.prototype.filter:
var data = [
{ id: 3, name: 'Bear' },
{ id: 4, name: 'Teddy' },
{ id: 5, name: 'Mouse' },
{ id: 1, name: 'Pedro' },
{ id: 2, name: 'Miko' },
],
need = [1, 3, 5],
filtered = data.filter(function (a) {
return ~need.indexOf(a.id);
});
document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');
In case the data set is small, you are ok with any of the offered solution (ones that use indexOf).
However, these solutions are O(n^2) ones, therefore, given the data set big enough, the lag can become noticeable. In this case, you should build an index prior to selecting elements.
Example:
function filterFast(data, ids) {
var index = ids.reduce(function(a,b) {a[b] = 1; return a;}, {});
return data.filter(function(item) {
return index[item.id] === 1;
});
}
And some benchmarking can be tested here.
You can use the filter method on your Array:
var data = [
{ id:1, name: 'Pedro'},
{ id:2, name: 'Miko'},
{ id:3, name: 'Bear'},
{ id:4, name: 'Teddy'},
{ id:5, name: 'Mouse'}
];
var ids = [1, 3, 5];
var filteredData = filterData(data, 'id', ids[1]);
function filterData(data, prop, values) {
return data.filter(function(item) {
return ~values.indexOf(item[prop]); // ~ returns 0 if indexOf returns -1
});
}
See it in action in this JSFiddle.
Or if you are using jQuery, another option may be:
var arr1 = [1, 3, 5],
arr2 = [{ id: 1, name: 'Pedro' },
{ id: 2, name: 'Miko' },
{ id: 3, name: 'Bear' },
{ id: 4, name: 'Teddy' },
{ id: 5, name: 'Mouse' }],
filtered = $.grep(arr2, function (item) {
if (arr1.indexOf(item.id) > -1) {
return true;
}
});
You can use a for loop on the object array and check hasOwnProperty in another for loop for each ids in [1,3,5] (break out of the loop once an id found). (And break out of the bigger for-loop once all ids are found) If your array object is ordered (e.g. elements sorted from smallest id to biggest id) and so are your list, this solution should be quite efficient.
var c = 0;
for(var i =0; i< objects.length; i++){
for(var v =0; v< list.length; v++)
if(objects[i].hasOwnProperty(list[v])){
delete objects[i]; c++; break;
}
if(c===list.length) break;
}
or use array.splice( i, 1 ); if you don't want an empty slot.
Using filter and indexOf will do the trick:
var filteredArray = dataArray.filter(function(obj) {
return idsArray.indexOf(obj.id) > -1;
});
However, indexOf has linear performance, and it will be called lots of times.
In ES6 you can use a set instead, whose has call has sublinear performance (on average):
var idsSet = new Set(idsArray),
filteredArray = dataArray.filter(obj => idsSet.has(obj.id));
Assuming the toString method of your ids is injective, you can achieve something similar in ES5:
var idsHash = Object.create(null);
idsArray.forEach(function(id) {
idsHash[id] = true;
});
var filteredArray = dataArray.filter(function(obj) {
return idsHash[obj.id];
});