Remove objects with empty values from array / Javascript - javascript

I have an array of objects:
let arr = [{id:0, value: 'zero'},
{id:1, value: 'one'},
{id:2, value: ''}]
I need to remove object with empty value. What I am trying:
const removeEmpty = (arr) => {
let filtered = arr.filter(val => val.value != '');
return filtered;
};
Stuck with this:
TypeError: Cannot read property 'filter' of undefined
Edit: corrected syntax

IMHO, you are looking for something like this:
var arr = [{id:0, value: 'zero'}, {id:1, value: 'one'}, {id:2, value: ''}];
var filteredArr = arr.filter(obj => obj.value != '')
console.log(filteredArr);
NOTE: Your's is not a proper array (because Objects inside it are invalid).

You missed a comma on the value of id and a quote for the value of the value property
let arr = [{id:0, value: "zero"},
{id:1, value: "one"},
{id:2, value: ''}];
console.log(arr.filter(a => a.value != ''));

Seems your arr is not correct i.e object key value pair is not valid
let arr = [{id:0, value: 'zero'}, {id:1, value: 'one'}, {id:2, value: ''}];
const removeEmpty = (arr) => {
let filtered = arr.filter(val => val.value !== '');
return filtered;
}
removeEmpty(arr)

This questions is already answered in below link, Please have a look
Click here!

Following code will be helpful in more cases, for instance if object value is: false, null, empty string or undefined.
let arr = [
{id:0, value: 'zero'},
{id:1, value: 'one'},
{id:2, value: ''},
{id:3, value: false},
{id:4, value: null},
{id:5}
];
const filteredArr = arr.filter(obj => obj.value);
console.log(filteredArr);

Related

Filter array of objects but return only specific properties - JS [duplicate]

This question already has answers here:
Extract certain properties from all objects in array
(5 answers)
Closed 4 months ago.
How to filter an array of objects with a condition and return only specific properties of filtered objects?
I know we can use filter followed by map to achieve this. But I am looking for more simple solution.
For ex:
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}]
Suppose if I want only ids of name "lala".
Output should be,
[{id: 1}, {id: 3}]
The next simplest would be reduce
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}];
console.log(
arr.reduce((values, value) =>
{
if (value.name === 'lala') values.push({ id: value.id });
return values;
}, [])
);
You can simply use Array.prototype.reduce to combine both mapping and filtering in the same operation. If you want to make it super concise, you can use object destructuring in the second argument of the reduce callback:
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}];
let filteredMappedArr = arr.reduce((acc, { name, id }) => {
if (name === 'lala')
acc.push({ id });
return acc;
}, []);
console.log(filteredMappedArr);
filter followed by map is probably the most readable solution, but if you're looking to do it all in one step, you're looking at the classic for loop or using reduce.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
You can do it by using filter and map;
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}]
let res = arr.filter(item => item.id % 2 === 1).map(item => ({id: item.id}))
console.log(res);
You could take Array#flatMap and return either a new obejct or an empty array which has no value for flattening.
let array = [{ name: "lala", id: 1 }, { name: "coco", id: 2 }, { name: "lala", id: 3 }],
result = array.flatMap(({ id, name }) => name === 'lala' ? [{ id }] : []);
console.log(result);
using .filter() and .map() functions:
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}]
let newArr = arr.filter((elm) => (elm.name === 'lala')).map( (elm) => {return {id:elm.id}});
console.log(newArr);
let arr = [
{ name: "lala", id: 1 },
{ name: "coco", id: 2 },
{ name: "lala", id: 3 },
];
let a = [];
arr.filter(({ name, id }) => {
if (name === "lala") {
a.push({ id });
}
});
console.log(a);
with filter we check for the condition where name matches 'lala' if yes then we push id to new array...that's simple

Compare an array of objects and an array of singular values

I have two arrays. One is filled with objects, the other is filled with values. See code below:
const data = [
{id: 1, name: 'ben'},
{id: 2, name: 'ben'},
{id: 3, name: 'ben'},
{id: 4, name: 'ben'}
];
const ids = [1,3,4,5]
I want to select only objects from the data array where the id property matches any of the value in the ids array.
How best should I go about this?
Thanks in advance
Here is a code snippet that might help.
const data = [{id:1, name:'ben'},{id:2, name:'ben'}, {id:3, name:'ben'}, {id:4, name:'ben'}];
const ids = [1,3,4,5];
const newData = data.filter(chunk => ids.includes(chunk.id));
console.log("Filtered Data", newData);
Easiest approach to do this is array filter function:
const data = [{id:1, name:'ben'},{id:2, name:'ben'}, {id:3, name:'ben'}, {id:4, name:'ben'}];
const ids = [1, 3, 4, 5];
const result = data.filter(({id}) => ids.includes(id));
console.log(result);
As an alternative way, you can use some method placed inside filter method:
data.filter(chunk => ids.some(s => s == chunk.id));
An example:
const data = [{id:1, name:'ben'},{id:2, name:'ben'}, {id:3, name:'ben'}, {id:4, name:'ben'}];
const ids = [1,3,4,5];
const newData = data.filter(chunk => ids.some(s => s== chunk.id));
console.log("Filtered Data", newData);
You can use Array.prototype.filter to filter the initial array and Array.prototype.includes to exclude unmatching entities:
const data = [
{ id: 1, name: "ben" },
{ id: 2, name: "ben" },
{ id: 3, name: "ben" },
{ id: 4, name: "ben" }
];
const ids = [1, 3, 4, 5];
const filteredData = data.filter(dataItem => ids.includes(dataItem.id));
console.log(filteredData); // [{"id":1,"name":"ben"},{"id":3,"name":"ben"},{"id":4,"name":"ben"}]

Return a subset of an array of objects that matches a property of an another array of objects

inputs:
const parentArray = [
{id:1, name:'foo'},
{id:2, name:'bar'},
{id:4, name:'foobar'},
{id:6, name:'barfoo'}
]
const childArray = [
{parent_id:1, prop:'prop1'},
{parent_id:2, prop:'prop2'},
{parent_id:3, prop:'prop3'},
{parent_id:4, prop:'prop4'},
{parent_id:5, prop:'prop5'}
];
output:
const resultingArray = [
{id:1, name:'foo'},
{id:2, name:'bar'},
{id:4, name:'foobar'}
]
I want to compare the properties id and parent_id from both arrays and return a subset of parentArray for the matching properties
I've tried to filter them out but not having success, using lodash
You could take a Set for the wanted parents and filter the parent array.
var parents = [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }],
children = [{ parent_id: 1, prop: 'prop1' }, { parent_id: 3, prop: 'prop3' }],
wanted = new Set(children.map(({ parent_id }) => parent_id)),
result = parents.filter(({ id }) => wanted.has(id));
console.log(result);
You can do so with a combination of Array.filter() and Array.some() in the following way.
const resultingArray = parentArray
.filter(x => childArray.some( y => y.parent_id===x.id));
Check this JS bin
We can use a Set as a lookup table for the parent_id data from the child and then use Array.prototype.filter to filter through the parent entries and use Set#has to check if the id is contained in the Set:
const parentArray = [{id:1, name:'foo'},{id:2, name:'bar'}, {id:4, name:'foo'},{id:6, name:'bar'}]
const childArray = [
{parent_id:1, prop:'prop1'},
{parent_id:2, prop:'prop2'},
{parent_id:3, prop:'prop3'},
{parent_id:4, prop:'prop4'},
{parent_id:5, prop:'prop5'}
];
function findSubSet(){
const lookup = new Set(childArray.map(({parent_id}) => parent_id));
return parentArray.filter(p => lookup.has(p.id));
}
console.log(findSubSet(parentArray, childArray));
You can use reduce & findIndex. In the reduce callback use findIndex to check if there exist same id.If id exist it will return the index & if not then it will return -1. So if index is not -1 then you can push the value to accumulator(acc)
const parentArray = [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
const childArray = [{
parent_id: 1,
prop: 'prop1'
},
{
parent_id: 2,
prop: 'prop2'
},
{
parent_id: 3,
prop: 'prop3'
}
]
let filteredData = parentArray.reduce(function(acc, curr) {
let getIndexFromChild = childArray.findIndex(function(item) {
return curr.id === item.parent_id
});
if (getIndexFromChild !== -1) {
acc.push(curr)
}
return acc;
}, []);
console.log(filteredData)
As previously mentioned, your example is unclear, but filtering an array using another array, assuming you want to use the properties id from parentArray and parent_id from childArray, then I would use this:
resultingArray = childArray.filter(c=> parentArray.find(p => p.id === c.parentId);
You can use a mixture of filter and some to get the matching values:
const parentArray = [{id:1, name:'foo'},{id:2, name:'bar'}]
const childArray = [
{parent_id:1, prop:'prop1'},
{parent_id:3, prop:'prop3'}
]
let result = parentArray.filter(i => childArray.some(j => j.parent_id == i.id))
console.log(result)

how to get a single field from array

I am using an array like below
var types = [{id:1, type:'Type 2'}, {id:2, type:'Type 5'}, {id:3, type:'Type 1'}, {id:4, type:'Type 2'}];
I want to filter values based on Type and get that into a single dimension array. I tried using filter etc. but gets the filtered 2-dimensional array.
$filter('filter')(types, { type: 'Type 2' })
Result should be just id array without type like:
[{id:1}, {id:4}]
Try with Array#map after the filter the array
var types = [{id:1, type:'Type 2'}, {id:2, type:'Type 5'}, {id:3, type:'Type 1'}, {id:4, type:'Type 2'}];
console.log(types.filter(a=> a.type =='Type 2' ).map(a=> ({id : a.id})))
true to its naming convention filter() will not manipulate object; it selects a new subset array.
You can use Array.map()
$filter('filter')(types, { type: 'Type 2' }).map(function(x){
return { id : x.id };
})
Working Fiddle :http://jsfiddle.net/ADukg/12074/
You can either use a combination of filter and map. Or, you can use this amazing function called reduce which can single-handedly filter as well as map your array. Like this:
var types = [{id:1, type:'Type 2'}, {id:2, type:'Type 5'}, {id:3, type:'Type 1'}, {id:4, type:'Type 2'}];
var res = types.reduce(function(arr, obj) {
if(obj.type === 'Type 2') {
arr.push({
id: obj.id
})
}
return arr
}, [])
console.log(res)
Hi Vikas Vaidya you can also use the following code to solve this problem:
function filterArrayofObjects(objKey, objValue) {
var temp = [], count = -1;
for (var i in types) {
var flag = false;
var obj = {};
for (var j in types[i]) {
if (j === objKey && types[i][j] === objValue) {
flag = true;
continue;
}
obj[j] = types[i][j];
}
if (flag) {
count++;
temp[count] = obj;
}
}
return temp;
}
var result = filterArrayofObjects("type", "Type 2");
window.console.log(result);
You can use Underscore js. _.filter and _.map can help you to achieve desired results

Filter an array of objects and extract its property by using an array of keys

im having this problem which i cant wrap around my head,
much better if put in a code.
//Array of objects sample
var objects = [{id:1, name:'test1'}, {id:2, name:'test2'}, {id:3, name: 'test3'}, {id:4, name:'test4'}];
var arrayOfKeys = [3,1,4];
//extract object name property if its id property is equivalent to one of arrayOfKeys [3,1]
//var arrayOfKeys = [3,1,4];
//output sample: extractedName=['test3','test1','test4'];
i've been using filter and map but no avail, also tried nesting filter inside map im getting an arrays of array and inside is a single object.
You could map the objects and ren map the wanted keys for getting the name.
var objects = [{ id: 1, name: 'test1' }, { id: 2, name: 'test2' }, { id: 3, name: 'test3' }],
arrayOfKeys = [3, 1],
result = arrayOfKeys.map((map => id => map.get(id).name)(new Map(objects.map(o => [o.id, o]))));
console.log(result);
I assume you need to map array numbers to id properties? Here's the code where you map through numbers and find inside your array to handle situations when there's no such id in objects array:
var objects = [{id:1, name:'test1'}, {id:2, name:'test2'}, {id:3, name: 'test3'}];
var arrayOfKeys = [3,1];
var res = arrayOfKeys.map(key => {
var found = objects.find(o => o.id == key);
return found ? found.name : false;
})
console.log(res)
let objects = [{id:1, name:'test1'}, {id:2, name:'test2'}, {id:3, name: 'test3'}, {id:4, name:'test4'}],
arrayOfKeys = [3,1,4];
let result = objects.reduce((res, obj) => { // loop over the array of objects
let index = arrayOfKeys.indexOf(obj.id); // check if the current object's id is in the array of keys
if(index !== -1) { // if it's there
res.push(obj.name); // then add the current object's name to the result array
arrayOfKeys.splice(index, 1); // remove its id from the array of keys so we won't search for it again (optional, slightly better than leaving it there)
}
return res;
}, []);
console.log(result);
I think you were on the right track with the filter. You can make it readable and concise with some.
var objects = [{id: 1,name: 'test1'}, {id: 2,name: 'test2'}, {id: 3,name: 'test3'}, {id: 4,name: 'test4'}],
arrayOfKeys = [3, 1, 4];
var result = objects.filter((x, i) => {
if (arrayOfKeys.some(k => x.id === k)) {
return true;
}
})
console.log(result.map(x=>x.name));
Something even shorter! would be
var objects = [{id: 1,name: 'test1'}, {id: 2,name: 'test2'}, {id: 3,name: 'test3'}, {id: 4,name: 'test4'}],arrayOfKeys = [3, 1, 4];
var result = objects.filter((x, i) => arrayOfKeys.some(k => x.id === k));
console.log(result.map(x=>x.name));

Categories