How to make the function loop through the Array - javascript

Having this Array of Objects:
let myFriends = [
{ title: "Osama", age: 39, available: true, skills: ["HTML", "CSS"] },
{ title: "Ahmed", age: 25, available: false, skills: ["Python", "Django"] },
{ title: "Sayed", age: 33, available: true, skills: ["PHP", "Laravel"] },
];
And this Variable:
let chosen = 2;
I need to Destruct it depending on the chosen variable to get something like this:
// If chosen === 1
"Osama"
39
"Available"
"CSS"
// If chosen === 2
"Ahmed"
25
"Not Available"
"Django"
// If chosen === 3
"Sayed"
33
"Available"
"Laravel"
I Tried this code:
switch (chosen) {
case 1:
const { title: t1, age: a1, available: av1, skills: s1 } = myFriends[0];
const [h1, c1] = myFriends[0].skills
console.log(t1)
console.log(a1)
console.log(av1 ? "Available" : "Not Available")
console.log(c1)
break;
case 2:
const { title: t2, age: a2, available: av2, skills: s2 } = myFriends[1];
const [h2, c2] = myFriends[1].skills
console.log(t2)
console.log(a2)
console.log(av2 ? "Available" : "Not Available")
console.log(c2)
break;
case 3:
const { title: t3, age: a3, available: av3, skills: s3 } = myFriends[2];
const [h3, c3] = myFriends[2].skills
console.log(t3)
console.log(a3)
console.log(av3 ? "Available" : "Not Available")
console.log(c3)
}
And it works, but I want to make a simpler code. So I tried this one:
function chosenPerson(chosen) {
const { title: t, age: a, available: av, skills: s } = myFriends[`${chosen}`];
const [h, c] = myFriends[`${chosen}`].skills
console.log(t)
console.log(a)
console.log(av ? "Available" : "Not Available")
console.log(c)
};
chosenPerson();
It didn't work, so how can i make the function change with the chosen variable

Thanks to #Teemu the problem was that I didn't pass chosen to the function call.
and there is no need to use this myFriends['${chosen}'].
all I needed were myFriends[chosen - 1] as the array is 0 based index, and to pass chosen to the function call like this chosenPerson(chosen)

let myFriends = [
{ title: "Osama", age: 39, available: true, skills: ["HTML", "CSS"] },
{ title: "Ahmed", age: 25, available: false, skills: ["Python", "Django"] },
{ title: "Sayed", age: 33, available: true, skills: ["PHP", "Laravel"] },
];
let choosen = 2;
function getDetail(option){
const {title, age, available, skills } = myFriends[option -1];
return [title, age, available ? "Available" : "Non Available" , skills.join(',')]
}
console.log(getDetail(choosen));
Try this solution which return output inside an array
I hope this will fix your problem.

Related

save different elements in array by a condition

How can I save elements in an array based on a condition? In the following array, if I pass an age, it returns the array with the elements that meet that condition, but if I pass an age that does not exist or nothing happens when calling the function, how can I add all the elements of array1 to array2
const array1 = [
{
name: 'jose',
country: 'argentina',
age: 20
},
{
name: 'pedro',
country: 'brazil',
age: 18
},
{
name: 'andrea',
country: 'mexico',
age: 20
},
{
name: 'luis',
country: 'eu',
age: 19
},
{
name: 'nancy',
country: 'mexico',
age: 18
}
];
const getDatos = (age) => {
const array2 = array2.filter(data=> data.age === age);
console.log(array2 )
}
getDatos(20);
not sure if this is what you want, but you can check if the age is in the array using Array.prototype.some(MDN documentation)
const getDatos = (age) => {
if (array1.some(data => data.age === age)) {
return array1.filter(data=> data.age === age);
} else {
return array1;
}
}
EDIT: Based on Sebastian Simons comment, this approach it's better
const getDatos = (age) => {
const results = array1.filter(data => data.age === age);
return results.length > 0 ? results : array1;
}
You can use the ternary operator ? to check the length of array returned by filter. If any matches are found, return them, otherwise return all records.
const all = [
{ name: 'jose', country: 'argentina', age: 20 },
{ name: 'pedro', country: 'brazil', age: 18 },
{ name: 'andrea', country: 'mexico', age: 20 },
{ name: 'luis', country: 'eu', age: 19 },
{ name: 'nancy', country: 'mexico', age: 18 }
];
const getDatos = (age) => {
let matches = all.filter(data => data.age === age);
return (matches.length) ? matches : all;
}
console.log(getDatos(20)); // jose & andrea
console.log(getDatos(99)); // all records

How to sort an array of objects based on another array with conditions

Can anyone help me know how to filter an array of objects based on another array holding multiple conditions.
Sample Array
const arrayToFilter = [
{
name: 'Renaldo Ca',
screen_name: 'rca0',
followers_count: 726,
following_count: 752,
location: 'Peru',
verified: true,
},
{
name: 'Bobbette Dibling',
screen_name: 'bdibling1',
followers_count: 747,
following_count: 613,
location: 'Argentina',
verified: true,
},
{
name: 'Obed Snelson',
screen_name: 'osnelson2',
followers_count: 466,
following_count: 352,
location: 'Russia',
verified: false,
},
{
name: 'Elyssa Eastop',
screen_name: 'eeastop3',
followers_count: 888,
following_count: 493,
location: 'Uganda',
verified: true,
},
{
name: 'Auroora Balogun',
screen_name: 'abalogun4',
followers_count: 688,
following_count: 468,
location: 'Brazil',
verified: true,
},
{
name: 'Sarge Crosser',
screen_name: 'scrosser5',
followers_count: 218,
following_count: 424,
location: 'United Kingdom',
verified: true,
},
{
name: 'Griswold Lardeur',
screen_name: 'glardeur6',
followers_count: 785,
following_count: 122,
location: 'South Korea',
verified: false,
},
{
name: 'Edwin Goodlatt',
screen_name: 'egoodlatt7',
followers_count: 484,
following_count: 611,
location: 'Indonesia',
verified: true,
}
]
Array With Filter Conditions:
const conditions=[
{
id: 'name',
operator: 'CONTAINS'
value: 'Bob',
},
{
condition:'AND',
id: 'followers_count',
operator: 'GTE'
value: 200,
},
{
condition:'AND',
id: 'following_count',
operator: 'LTE'
value: 10,
},
{
condition:'OR',
id: 'verified',
operator: 'EQ'
value: true,
}
]
The following code gives the filtered array but logic for AND/OR execution messesup.
const filterWithConditions = (arr, conditions) =>
arr.filter((item) =>
conditions.every(({ id, operator, value }) => {
switch (operator) {
case 'CONTAINS':
return item[id].toLowerCase().indexOf(value.toLowerCase()) > -1;
case 'GTE':
return item[id] >= value;
case 'LTE':
return item[id] <= value;
case 'EQ':
return item[id].toString() === value.toString();
default:
return false;
}
})
);
let filteredData = filterWithConditions(data, filters);
const alternateFilters = groupBy(filters, 'condition')['OR'];
if (alternateFilters) alternateFilters.map((filter) => filteredData.push(...filterWithConditions(data, [filter])));
const processedData = getUniqData(filteredData);
The code should return array filtered based on these conditions in with respect to the bitwise conditions too(AND/OR).
Please let me know the optimized code for this. Thanks in advance!
Codesandbox link: https://codesandbox.io/s/black-hooks-4bbsu
I did a small example. Change as you want. I put some comments for your understanding.
// Initial data
const objs = [
{
a: "a a a",
b: "b b b",
c: "c c c"
},
{
a: "a b a",
b: "b b b",
c: "c b c"
},
{
a: "a a c",
b: "b b c",
c: "c c c"
},
{
a: "a a b",
b: "b b c",
c: "c c c"
},
];
const conds = {
"like": (a,b)=>a.includes(b),
"eq": (a,b)=>a===b
};
const ops = {
"OR": (a,b)=>a||b,
"AND": (a,b)=>a&&b
}
const qrys = [
{
col: "a",
cond: "like",
val: "b"
},
{
col: "b",
cond: "eq",
val: "b b c",
op: "AND"
},
{
col: "c",
cond: "eq",
val: "b b c",
op: "OR"
},
{
col: "c",
cond: "eq",
val: "c c c",
op: "AND"
}
]
// Function
const filtered = objs.filter(obj=>{
let ret = false;
for(const qry of qrys) {
// Actual value of the object
const val = obj[qry.col];
// Comparing it with the expected value by given condition
const assert = conds[qry.cond](val, qry.val);
// Applying logical operators.
if(qry.op){
ret = ops[qry.op](ret, assert);
} else {
ret = assert;
}
}
return ret;
});
console.log(filtered);
I'm guessing this is how the logic should be applied:
Where the name contains bob
AND the followers count is gte 200
Where the name contains bob
AND the following count is lte 400
Where the name contains bob
OR the verified property is true
Based on the above assumption, I'd do it like this:
const result = (item,condition) => {
switch(condition.operator) {
case 'CONTAINS': return item[condition.id].contains(condition.value);
case 'GTE': return item[condition.id] >= condition.value;
case 'LTE': return item[condition.id] <= condition.value;
default: return false;
}
}
const results = arrayToFilter.filter(item => {
const baseCondition = conditions[0];
const baseResult = result(item,baseCondition);
// if there's only one condition, early return
if(conditions.length === 1) return baseCondition;
return conditions.slice(1).some(c => {
const r = result(item,c);
switch(c.condition) {
case 'AND': return baseCondition && r;
case 'OR': return baseCondition || r;
default: return false;
}
});
});
All this being said, the UI is confusing and should include the ability to nest conditions to make it clearer.
You could build a string and take eval for the data with the correct logical operators.
const
ops = {
EQ: (a, b) => a === b,
GTE: (a, b) => a >= b,
LTE: (a, b) => a <= b,
CONTAINS: (a, b) => a.toLowerCase().includes(b.toLowerCase()),
AND: (a, b) => a && b,
OR: (a, b) => a || b
},
filterBy = filters => o => filters.reduce((r, { condition, id, operator, value }) => (ops[condition] || ops.OR)(r, ops[operator](o[id], value)), false),
data = [{ name: 'Renaldo Ca', screen_name: 'rca0', followers_count: 726, following_count: 752, location: 'Peru', verified: false }, { name: 'Bobbette Dibling', screen_name: 'bdibling1', followers_count: 747, following_count: 613, location: 'Argentina', verified: true }, { name: 'Obed Snelson', screen_name: 'osnelson2', followers_count: 466, following_count: 352, location: 'Russia', verified: false }, { name: 'Elyssa Eastop', screen_name: 'eeastop3', followers_count: 888, following_count: 493, location: 'Uganda', verified: true }, { name: 'Auroora Balogun', screen_name: 'abalogun4', followers_count: 688, following_count: 468, location: 'Brazil', verified: true }, { name: 'Sarge Crosser', screen_name: 'scrosser5', followers_count: 218, following_count: 424, location: 'United Kingdom', verified: true }, { name: 'Griswold Lardeur', screen_name: 'glardeur6', followers_count: 785, following_count: 122, location: 'South Korea', verified: false }, { name: 'Edwin Goodlatt', screen_name: 'egoodlatt7', followers_count: 484, following_count: 611, location: 'Indonesia', verified: true }],
conditions = [{ id: 'name', operator: 'CONTAINS', value: 'Bob' }, { condition: 'AND', id: 'followers_count', operator: 'GTE', value: 200 }, { condition: 'AND', id: 'following_count', operator: 'LTE', value: 10 }, { condition: 'OR', id: 'verified', operator: 'EQ', value: true }],
result = data.filter(filterBy(conditions));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const items = [
{
name: 'Obed bob Snelson',
screen_name: 'osnelson2',
followers_count: 466,
following_count: 352,
location: 'Russia',
verified: false,
},
{
name: 'Elyssa Eastop',
screen_name: 'eeastop3',
followers_count: 888,
following_count: 493,
location: 'Uganda',
verified: true,
},
]
const conditions=[
{
id: 'name',
operator: 'CONTAINS',
value: 'Bob'
},
{
condition:'AND',
id: 'followers_count',
operator: 'GTE',
value: 200
}
];
const conditionCount = conditions.length
const itemsCount = items.length;
const results = [];
for(let index = 0; index < conditionCount; index++) {
for(let itemsIndex = 0; itemsIndex < itemsCount; itemsIndex++) {
switch(conditions[index]['operator']) {
case "CONTAINS":
if(items[itemsIndex][conditions[index]['id']].includes(conditions[index]['value']))
results.push(items[itemsIndex])
break;
case "GTE":
if(items[itemsIndex][conditions[index]['id']] >= conditions[index]['value'])
results.push(items[itemsIndex])
break;
}
}
}
console.log(results);
I did not include all operators, but hey....you should be able to figure the rest out yourself I think :). It about the idea I propose.

Using Javascript Array Properties to restrict a random output [duplicate]

I want to simplify an array of objects. Let's assume that I have following array:
var users = [{
name: 'John',
email: 'johnson#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom#mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark#mail.com',
age: 28,
address: 'England'
}];
And filter object:
var filter = {address: 'England', name: 'Mark'};
For example i need to filter all users by address and name, so i do loop through filter object properties and check it out:
function filterUsers (users, filter) {
var result = [];
for (var prop in filter) {
if (filter.hasOwnProperty(prop)) {
//at the first iteration prop will be address
for (var i = 0; i < filter.length; i++) {
if (users[i][prop] === filter[prop]) {
result.push(users[i]);
}
}
}
}
return result;
}
So during first iteration when prop - address will be equal 'England' two users will be added to array result (with name Tom and Mark), but on the second iteration when prop name will be equal Mark only the last user should be added to array result, but i end up with two elements in array.
I have got a little idea as why is it happening but still stuck on it and could not find a good solution to fix it. Any help is appreciable. Thanks.
You can do like this
var filter = {
address: 'England',
name: 'Mark'
};
var users = [{
name: 'John',
email: 'johnson#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom#mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark#mail.com',
age: 28,
address: 'England'
}
];
users= users.filter(function(item) {
for (var key in filter) {
if (item[key] === undefined || item[key] != filter[key])
return false;
}
return true;
});
console.log(users)
If you know the name of the filters, you can do it in a line.
users = users.filter(obj => obj.name == filter.name && obj.address == filter.address)
Another take for those of you that enjoy succinct code.
NOTE: The FILTER method can take an additional this argument, then using an E6 arrow function we can reuse the correct this to get a nice one-liner.
var users = [{name: 'John',email: 'johnson#mail.com',age: 25,address: 'USA'},
{name: 'Tom',email: 'tom#mail.com',age: 35,address: 'England'},
{name: 'Mark',email: 'mark#mail.com',age: 28,address: 'England'}];
var query = {address: "England", name: "Mark"};
var result = users.filter(search, query);
function search(user){
return Object.keys(this).every((key) => user[key] === this[key]);
}
// |----------------------- Code for displaying results -----------------|
var element = document.getElementById('result');
function createMarkUp(data){
Object.keys(query).forEach(function(key){
var p = document.createElement('p');
p.appendChild(document.createTextNode(
key.toUpperCase() + ': ' + result[0][key]));
element.appendChild(p);
});
}
createMarkUp(result);
<div id="result"></div>
Here is ES6 version of using arrow function in filter. Posting this as an answer because most of us are using ES6 these days and may help readers to do filter in advanced way using arrow function, let and const.
const filter = {
address: 'England',
name: 'Mark'
};
let users = [{
name: 'John',
email: 'johnson#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom#mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark#mail.com',
age: 28,
address: 'England'
}
];
users= users.filter(item => {
for (let key in filter) {
if (item[key] === undefined || item[key] != filter[key])
return false;
}
return true;
});
console.log(users)
users.filter(o => o.address == 'England' && o.name == 'Mark')
Much better for es6. or you can use || (or) operator like this
users.filter(o => {return (o.address == 'England' || o.name == 'Mark')})
Can also be done this way:
this.users = this.users.filter((item) => {
return (item.name.toString().toLowerCase().indexOf(val.toLowerCase()) > -1 ||
item.address.toLowerCase().indexOf(val.toLowerCase()) > -1 ||
item.age.toLowerCase().indexOf(val.toLowerCase()) > -1 ||
item.email.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
Using Array.Filter() with Arrow Functions we can achieve this using
users = users.filter(x => x.name == 'Mark' && x.address == 'England');
Here is the complete snippet
// initializing list of users
var users = [{
name: 'John',
email: 'johnson#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom#mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark#mail.com',
age: 28,
address: 'England'
}
];
//filtering the users array and saving
//result back in users variable
users = users.filter(x => x.name == 'Mark' && x.address == 'England');
//logging out the result in console
console.log(users);
Improving on the good answers here, below is my solution:
const rawData = [
{ name: 'John', email: 'johnson#mail.com', age: 25, address: 'USA' },
{ name: 'Tom', email: 'tom#mail.com', age: 35, address: 'England' },
{ name: 'Mark', email: 'mark#mail.com', age: 28, address: 'England' }
]
const filters = { address: 'England', age: 28 }
const filteredData = rawData.filter(i =>
Object.entries(filters).every(([k, v]) => i[k] === v)
)
I think this might help.
const filters = ['a', 'b'];
const results = [
{
name: 'Result 1',
category: ['a']
},
{
name: 'Result 2',
category: ['a', 'b']
},
{
name: 'Result 3',
category: ['c', 'a', 'b', 'd']
}
];
const filteredResults = results.filter(item =>
filters.every(val => item.category.indexOf(val) > -1)
);
console.log(filteredResults);
Dynamic filters with AND condition
Filter out people with gender = 'm'
var people = [
{
name: 'john',
age: 10,
gender: 'm'
},
{
name: 'joseph',
age: 12,
gender: 'm'
},
{
name: 'annie',
age: 8,
gender: 'f'
}
]
var filters = {
gender: 'm'
}
var out = people.filter(person => {
return Object.keys(filters).every(filter => {
return filters[filter] === person[filter]
});
})
console.log(out)
Filter out people with gender = 'm' and name = 'joseph'
var people = [
{
name: 'john',
age: 10,
gender: 'm'
},
{
name: 'joseph',
age: 12,
gender: 'm'
},
{
name: 'annie',
age: 8,
gender: 'f'
}
]
var filters = {
gender: 'm',
name: 'joseph'
}
var out = people.filter(person => {
return Object.keys(filters).every(filter => {
return filters[filter] === person[filter]
});
})
console.log(out)
You can give as many filters as you want.
In lodash,
_.filter(users,{address: 'England', name: 'Mark'})
In es6,
users.filter(o => o.address == 'England' && o.name == 'Mark')
You'll have more flexibility if you turn the values in your filter object into arrays:
var filter = {address: ['England'], name: ['Mark'] };
That way you can filter for things like "England" or "Scotland", meaning that results may include records for England, and for Scotland:
var filter = {address: ['England', 'Scotland'], name: ['Mark'] };
With that setup, your filtering function can be:
const applyFilter = (data, filter) => data.filter(obj =>
Object.entries(filter).every(([prop, find]) => find.includes(obj[prop]))
);
// demo
var users = [{name: 'John',email: 'johnson#mail.com',age: 25,address: 'USA'},{name: 'Tom',email: 'tom#mail.com',age: 35,address: 'England'},{name: 'Mark',email: 'mark#mail.com',age: 28,address: 'England'}];var filter = {address: ['England'], name: ['Mark'] };
var filter = {address: ['England'], name: ['Mark'] };
console.log(applyFilter(users, filter));
If you want to put multiple conditions in filter, you can use && and || operator.
var product= Object.values(arr_products).filter(x => x.Status==status && x.email==user)
A clean and functional solution
const combineFilters = (...filters) => (item) => {
return filters.map((filter) => filter(item)).every((x) => x === true);
};
then you use it like so:
const filteredArray = arr.filter(combineFilters(filterFunc1, filterFunc2));
and filterFunc1 for example might look like this:
const filterFunc1 = (item) => {
return item === 1 ? true : false;
};
We can use different operators to provide multiple condtion to filter the array in the following way
Useing OR (||) Operator:
const orFilter = [{a:1, b: 3}, {a:1,b:2}, {a: 2, b:2}].filter(d => (d.a !== 1 || d.b !== 2))
console.log(orFilter, 'orFilter')
Using AND (&&) Operator:
const andFilter = [{a:1, b: 3}, {a:1,b:2}, {a: 2, b:2}].filter(d => (d.a !== 1 && d.b !== 2))
console.log(andFilter, 'andFilter')
functional solution
function applyFilters(data, filters) {
return data.filter(item =>
Object.keys(filters)
.map(keyToFilterOn =>
item[keyToFilterOn].includes(filters[keyToFilterOn]),
)
.reduce((x, y) => x && y, true),
);
}
this should do the job
applyFilters(users, filter);
My solution, based on NIKHIL C M solution:
let data = [
{
key1: "valueA1",
key2: "valueA2",
key3: []
},{
key1: "valueB1",
key2: "valueB2"
key3: ["valuesB3"]
}
];
let filters = {
key1: "valueB1",
key2: "valueB2"
};
let filteredData = data.filter((item) => {
return Object.entries(filters).every(([filter, value]) => {
return item[filter] === value;
//Here i am applying a bit more logic like
//return item[filter].includes(value)
//or filter with not exactly same key name like
//return !isEmpty(item.key3)
});
});
A question I was in the middle of answering got (properly) closed as duplicate of this. But I don't see any of the answers above quite like this one. So here's one more option.
We can write a simple function that takes a specification such as {name: 'mike', house: 'blue'}, and returns a function that will test if the value passed to it matches all the properties. It could be used like this:
const where = (spec, entries = Object .entries (spec)) => (x) =>
entries .every (([k, v]) => x [k] == v)
const users = [{name: 'John', email: 'johnson#mail.com', age: 25, address: 'USA'}, {name: 'Mark', email: 'marcus#mail.com', age: 25, address: 'USA'}, {name: 'Tom', email: 'tom#mail.com', age: 35, address: 'England'}, {name: 'Mark', email: 'mark#mail.com', age: 28, address: 'England'}]
console .log ('Mark', users .filter (where ({name: 'Mark'})))
console .log ('England', users .filter (where ({address: 'England'})))
console .log ('Mark/England', users .filter (where ({name: 'Mark', address: 'England'})))
.as-console-wrapper {max-height: 100% !important; top: 0}
And if we wanted to wrap the filtering into a single function, we could reuse that same function, wrapped up like this:
const where = (spec, entries = Object .entries (spec)) => (x) =>
entries .every (([k, v]) => x [k] == v)
const filterBy = (spec) => (xs) =>
xs .filter (where (spec))
const users = [{name: 'John', email: 'johnson#mail.com', age: 25, address: 'USA'}, {name: 'Mark', email: 'marcus#mail.com', age: 25, address: 'USA'}, {name: 'Tom', email: 'tom#mail.com', age: 35, address: 'England'}, {name: 'Mark', email: 'mark#mail.com', age: 28, address: 'England'}]
console .log ('Mark/England', filterBy ({address: "England", name: "Mark"}) (users))
.as-console-wrapper {max-height: 100% !important; top: 0}
(Of course that last doesn't have to be curried. We could change that so that we could call it with two parameters at once. I find this more flexible, but YMMV.)
Keeping it as a separate function has the advantage that we could then reuse it, in say, a find or some other matching situation.
This design is very similar to the use of where in Ramda (disclaimer: I'm one of Ramda's authors.) Ramda offers the additional flexibility of allowing arbitrary predicates instead of values that have to be equal. So in Ramda, you might write something like this instead:
filter (where ({
address: equals ('England')
age: greaterThan (25)
}) (users)
It's much the same idea, only a bit more flexible.
If the finality of you code is to get the filtered user, I would invert the for to evaluate the user instead of reducing the result array during each iteration.
Here an (untested) example:
function filterUsers (users, filter) {
var result = [];
for (i=0;i<users.length;i++){
for (var prop in filter) {
if (users.hasOwnProperty(prop) && users[i][prop] === filter[prop]) {
result.push(users[i]);
}
}
}
return result;
}
with the composition of some little helpers:
const filter = {address: 'England', name: 'Mark'};
console.log(
users.filter(and(map(propMatches)(filter)))
)
function propMatches<T>(property: string, value: any) {
return (item: T): boolean => item[property] === value
}
function map<T>(mapper: (key: string, value: any, obj: T) => (item:T) => any) {
return (obj: T) => {
return Object.keys(obj).map((key) => {
return mapper(key, obj[key], obj)
});
}
}
export function and<T>(predicates: ((item: T) => boolean)[]) {
return (item: T) =>
predicates.reduce(
(acc: boolean, predicate: (item: T) => boolean) => {
if (acc === undefined) {
return !!predicate(item);
}
return !!predicate(item) && acc;
},
undefined // initial accumulator value
);
}
This is an easily understandable functional solution
let filtersObject = {
address: "England",
name: "Mark"
};
let users = [{
name: 'John',
email: 'johnson#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom#mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark#mail.com',
age: 28,
address: 'England'
}
];
function filterUsers(users, filtersObject) {
//Loop through all key-value pairs in filtersObject
Object.keys(filtersObject).forEach(function(key) {
//Loop through users array checking each userObject
users = users.filter(function(userObject) {
//If userObject's key:value is same as filtersObject's key:value, they stay in users array
return userObject[key] === filtersObject[key]
})
});
return users;
}
//ES6
function filterUsersES(users, filtersObject) {
for (let key in filtersObject) {
users = users.filter((userObject) => userObject[key] === filtersObject[key]);
}
return users;
}
console.log(filterUsers(users, filtersObject));
console.log(filterUsersES(users, filtersObject));
This is another method i figured out, where filteredUsers is a function that returns the sorted list of users.
var filtersample = {address: 'England', name: 'Mark'};
filteredUsers() {
return this.users.filter((element) => {
return element['address'].toLowerCase().match(this.filtersample['address'].toLowerCase()) || element['name'].toLowerCase().match(this.filtersample['name'].toLowerCase());
})
}
const users = [{
name: 'John',
email: 'johnson#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom#mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark#mail.com',
age: 28,
address: 'England'
}
];
const filteredUsers = users.filter(({ name, age }) => name === 'Tom' && age === 35)
console.log(filteredUsers)
Using lodash and not pure javascript
This is actually quite simple using lodash and very easy to add/modify filters.
import _ from 'lodash';
async getUsersWithFilter(filters) {
const users = yourArrayOfSomethingReally();
// Some properties of the 'filters' object can be null or undefined, so create a new object without those undefined properties and filter by those who are defined
const filtersWithoutUndefinedValuesObject = _.omitBy(
filters,
_.isNil,
);
return _.filter(users, { ...filtersWithoutUndefinedValuesObject });
}
The omitBy function checks your filters object and removes any value that is null or undefined (if you take it out, the lodash.filter function wont return any result.
The filter function will filter out all the objects who's values don't match with the object you pass as a second argument to the function (which in this case, is your filters object.)
Why use this?
Well, assume you have this object:
const myFiltersObj = {
name: "Java",
age: 50
};
If you want to add another filter, just add a new property to the myFilterObj, like this:
const myFiltersObj = {
name: "Java",
email: 50,
country: "HND"
};
Call the getUsersWithFilter function, and it will work just fine. If you skip, let's say the name property in the object, the getUsersWithFilter function will filter by the email and country just fine.
Please check below code snippet with data you provided, it will return filtered data on the basis of multiple columns.
var filter = {
address: 'India',
age: '27'
};
var users = [{
name: 'Nikhil',
email: 'nikhil#mail.com',
age: 27,
address: 'India'
},
{
name: 'Minal',
email: 'minal#mail.com',
age: 27,
address: 'India'
},
{
name: 'John',
email: 'johnson#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom#mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark#mail.com',
age: 28,
address: 'England'
}
];
function filterByMultipleColumns(users, columnDataToFilter) {
return users.filter(row => {
return Object.keys(columnDataToFilter).every(propertyName => row[propertyName].toString().toLowerCase().indexOf(columnDataToFilter[propertyName].toString().toLowerCase()) > -1);
})
}
var filteredData = filterByMultipleColumns(users, filter);
console.log(filteredData);
Result :
[ { "name": "Nikhil", "email": "nikhil#mail.com", "age": 27, "address": "India" }, { "name": "Minal", "email": "minal#mail.com", "age": 27, "address": "India" } ]
Please check below link which can used with just small changes
Javascript filter array multiple values – example
const data = [{
realName: 'Sean Bean',
characterName: 'Eddard “Ned” Stark'
}, {
realName: 'Kit Harington',
characterName: 'Jon Snow'
}, {
realName: 'Peter Dinklage',
characterName: 'Tyrion Lannister'
}, {
realName: 'Lena Headey',
characterName: 'Cersei Lannister'
}, {
realName: 'Michelle Fairley',
characterName: 'Catelyn Stark'
}, {
realName: 'Nikolaj Coster-Waldau',
characterName: 'Jaime Lannister'
}, {
realName: 'Maisie Williams',
characterName: 'Arya Stark'
}];
const filterKeys = ['realName', 'characterName'];
const multiFilter = (data = [], filterKeys = [], value = '') => data.filter((item) => filterKeys.some(key => item[key].toString().toLowerCase().includes(value.toLowerCase()) && item[key]));
let filteredData = multiFilter(data, filterKeys, 'stark');
console.info(filteredData);
/* [{
"realName": "Sean Bean",
"characterName": "Eddard “Ned” Stark"
}, {
"realName": "Michelle Fairley",
"characterName": "Catelyn Stark"
}, {
"realName": "Maisie Williams",
"characterName": "Arya Stark"
}]
*/
arr.filter((item) => {
if(condition)
{
return false;
}
return true;
});

I want to replace null value to string and change the decimal points in javascript array

I'm trying to display user's data in table.
but I want to show the null value as '-' and only shows 2decimal points. ex)2.18,1.29
I was trying to use forEach like this
forEach((x)=>{
if(x.age===null){
x.age='-'
}
})
but this code is not useful because I always needs to put x.age or x.extrapoint ,
so my Idea is replace all the value in object..
const user = [
{ name: 'jenny', age: null, points: 56.9987,extraPoint:null },
{ name: 'david', age: 56, points: 56.324355,extraPoint:8 },
{ name: 'dude', age: null, points: 20.9987,extraPoint:null }
];
output should be
'jenny', '-', 56.9
'david', 56, 56.3,
'dude', '-',20.9
Try to using the map function as below:
user = user.map((x)=>{
if(!x.age){
x.age = '-'
}
return x;
})
You could map with a check for the values.
const
replaceNull = v => v === null ? '-': v
user = [{ name: 'jenny', age: null, points: 56.9987, extraPoint: null }, { name: 'david', age: 56, points: 56.324355, extraPoint: 8 }, { name: 'dude', age: null, points: 20.9987, extraPoint: null }],
result = user.map(o => [
replaceNull(o.name),
replaceNull(o.age),
o.points === null ? '-' : o.points.toFixed(2),
]);
console.log(result);
Here's my approach:
const user = [
{ name: 'jenny', age: null, points: 56.9987,extraPoint:null },
{ name: 'david', age: 56, points: 56.324355,extraPoint:8 },
{ name: 'dude', age: null, points: 20.9987,extraPoint:null }
];
for (const ind of Object.keys(user))
console.log(`${user[ind].name}, ${user[ind].age || '-'}, ${user[ind].points.toFixed(2)}`);
You can try to use map function, like this:
const user = [
{ name: 'jenny', age: null, points: 56.9987,extraPoint:null },
{ name: 'david', age: 56, points: 56.324355,extraPoint:8 },
{ name: 'dude', age: null, points: 20.9987,extraPoint:null }
];
var output = user.map(x => ({ name: x.name, age: x.age || '-', points: x.points.toFixed(2)}));
console.log(output);
Update:
If you want the number exactly (like 56.9 56.3 20.9), you can try to convert the number to a string and split it:
const user = [
{ name: 'jenny', age: null, points: 56.9987,extraPoint:null },
{ name: 'david', age: 56, points: 56.324355,extraPoint:8 },
{ name: 'dude', age: null, points: 20.9987,extraPoint:null }
];
var output = user.map(x => [x.name, x.age || '-', Number(x.points.toString().slice(0, 4))]);
console.log(output);
Use Object.keys() to dynamically enumerate and loop over object properties, you won't need to reference any of the properties in your code by name
const user = [
{ name: 'jenny', age: null, points: 56.9987,extraPoint:null },
{ name: 'david', age: 56, points: 56.324355,extraPoint:8 },
{ name: 'dude', age: null, points: 20.9987,extraPoint:null }
];
for(var i=0;i<user.length;i++){
let temp = {};
for (var key of Object.keys(user[i])) {
temp[key] = user[i][key] || '-'
}
user[i] = temp;
}
console.log(user);

Filter array and reset the index too

I have an array of objects like this:
const data = [
{
name: "Peter",
age: 20,
nationality: "American",
index: 0
},
{
name: "David",
age: 25,
nationality: "English",
index: 1
},
{
name: "Gabriel",
age: 23,
nationality: "Spanish",
index: 2
},
{
name: "Kate",
age: 22,
nationality: "English",
index: 3
},
];
If I want to return a new array with only the people with English nationality I'd use filter, like this:
let englishPerson = data.filter(el => el.nationality === 'English');
console.log(englishPerson);
And this will log the following:
> Array [Object { name: "David", age: 25, nationality: "English", index: 1 }, Object { name: "Kate", age: 22, nationality: "English", index: 3 }]
But I would like to reset the index after the data is filtered, so the first object in the new filtered array should have an index of 0, second an index of 1 and so on. In this case David has an index of 1, because it kept the same index from the original data.
You could filter followed by map, but it would be better to do it in one go with reduce - if the item passes the test, add it to the accumulator, with the index of the accumulator's current length:
const data=[{name:"Peter",age:20,nationality:"American",index:0},{name:"David",age:25,nationality:"English",index:1},{name:"Gabriel",age:23,nationality:"Spanish",index:2},{name:"Kate",age:22,nationality:"English",index:3},]
console.log(
data.reduce((a, item) => {
if (item.nationality === 'English') {
a.push({
...item,
index: a.length
});
}
return a;
}, [])
);
You can use Array.prototype.map() to modify the index property of the filtered result:
const data = [
{
name: "Peter",
age: 20,
nationality: "American",
index: 0
},
{
name: "David",
age: 25,
nationality: "English",
index: 1
},
{
name: "Gabriel",
age: 23,
nationality: "Spanish",
index: 2
},
{
name: "Kate",
age: 22,
nationality: "English",
index: 3
},
];
let i=0;
let englishPerson = data.filter(el => el.nationality === 'English').map(el => {
el.index = i; i++;
return el;
});
console.log(englishPerson);
Updated answer based on your comments:
const data = [
{
name: "Peter",
age: 20,
nationality: "American",
index: 0
},
{
name: "David",
age: 25,
nationality: "English",
index: 1
},
{
name: "Gabriel",
age: 23,
nationality: "Spanish",
index: 2
},
{
name: "Kate",
age: 22,
nationality: "English",
index: 3
},
];
let i=0;
let englishPerson = data.filter(el => el.nationality === 'English').map(el => {
if(el.hasOwnProperty('index')){
el.index = i; i++;
}
return el;
});
console.log(englishPerson);
If you want use your solution, with the slightest change, you can try this:
var c=0;
var englishPerson=data.filter(function(el){
return el.nationality=="English" && (el.index=c++)>-1;
});
console.log(englishPerson);
Do this:
const data = [
{
name: "Peter",
age: 20,
nationality: "American",
index: 0
},
{
name: "David",
age: 25,
nationality: "English",
index: 1
},
{
name: "Gabriel",
age: 23,
nationality: "Spanish",
index: 2
},
{
name: "Kate",
age: 22,
nationality: "English",
index: 3
},
];
data.filter(el => Object.values(el).includes('English')).forEach((obj, i) => {obj.index = i; console.log(obj)})
If you want to go with map, then just replace forEachwith map!
You can use from filters.tags.data.map(f => f.Key).toString() replace filter.
Where you use from the map, that index been reset.
For example:
$scope.ret = function(){
data: url,
method: post,
retuen filters.tags.data.map(f => f.Key).toString();
}

Categories