Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  12] [ 3]  / answers: 1 / hits: 26412  / 8 Years ago, sun, june 26, 2016, 12:00:00

I have an array of objects in this format:



var full_list = [
{
pid: 1,
items:[
{item_id: '9'},
{item_id: '10'},
{item_id: '12'}
]
},
{
pid: 2,
items:[
{item_id: '33'},
{item_id: '22'},
{item_id: '65'}
]
}...
];


I have a tmp array which consists of objects from the full array:



 var tmp_list =  [
{
pid: 2,
items:[
{item_id: '33'},
{item_id: '22'},
{item_id: '65'}
]
}, {....}


I would like to filter out objects from the full list where at least one of selectedIDs values appears in the object's item's id array



var selectedIDs = {'1', '9', '45', ....};


and then add them to the tmp list.



I tried using filters but I failed to figure it out completely.



Thank you.



selectedIDs.forEach(function(id) {
var tmp = full_list.filter(function (obj) {
obj.items.forEach(function (item) {
if (item.id === id) {
console.log('found');
}
});
});
tmp_list.push(tmp);
});

More From » arrays

 Answers
3

First of all, this line in your question is wrong



var selectedIDs = {'1', '9', '45', ....};



You cannot declare arrays using {}. Instead use []



For your problem you can use a pure functional approach using Array#filter and Array#some methods to get your desired result as below:





var full_list = [
{
pid: 1,
items:[
{item_id: '9'},
{item_id: '10'},
{item_id: '12'}
]
},
{
pid: 2,
items:[
{item_id: '33'},
{item_id: '22'},
{item_id: '67'}
]
},
{
pid: 9,
items:[
{item_id: '33'},
{item_id: '22'},
{item_id: '65'}
]
},
{
pid: 7,
items:[
{item_id: '7'},
{item_id: '22'},
{item_id: '65'}
]
}
];

var tmp_list = [
{
pid: 2,
items:[
{item_id: '7'},
{item_id: '22'},
{item_id: '65'}
]
}
];


function filterResult (selectedItems) {
return full_list.filter(function (process) {
return process.items.some(function(item){
return selectedItems.indexOf(item.item_id) > -1;
});
});
}

var selectedItems = ['9', '7', '22', '10'];

tmp_list = tmp_list.concat(filterResult(selectedItems))

console.log(tmp_list);


function flattenResults(list, selections) {
return list.reduce(function (accumulator, current) {
var res = current.items.filter(function(item){
return (selections.indexOf(item.item_id) > -1
&& checkIfAlreadyExist());

function checkIfAlreadyExist () {
return accumulator.every(function (k) {
return k.item_id !== item.item_id;
});
}
});

return accumulator.concat(res);
}, []);
}

console.log(flattenResults(full_list, selectedItems));




[#61629] Friday, June 24, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jordenfabiand

Total Points: 678
Total Questions: 107
Total Answers: 95

Location: Western Sahara
Member since Mon, May 3, 2021
3 Years ago
;