I have an array of objects:
items: [
{ name: "Cheese Puffs", price: 3 },
{ name: "Can of Soda", price: 1.75 }
];
I want to do something like items["cheesePuffs"] === true. But as it is in an array it won't work properly.
What you want is Array.find().
myArrOfObjects.find(el => el.cheesePuffs);
Assuming the property you're looking for is truthy, this returns the element, {cheesePuffs: "yes"} which is truthy. If it weren't found, it would be undefined.
You can use some and hasOwnProperty, If you need actual value instead of Boolean values you can use find instead of some
const myArrOfObjects = [{
cheesePuffs: "yes"
},
{
time: "212"
}];
let findByName = (name) => {
return myArrOfObjects.some(obj=> {
return obj.hasOwnProperty(name)
})
}
console.log(findByName("cheesePuffs"))
console.log(findByName("time"))
console.log(findByName("123"))
okay simple solutions
try this
const x = [{}];
if(x.find(el => el.cheesePuffs) == undefined)
console.log("empty objects in array ")
const myArrOfObjects = [{
cheesePuffs: "yes"
},
{
time: "212"
}];
if(myArrOfObjects.find(el => el.cheesePuffs) == undefined)
console.log("empty objects in array ")
else
console.log("objects available in array ")
As suggestion, you can also decide to not use an array, but to use a json object, where the index of each item is the unique name of your objects (in the example "cheesePuffs" identifies "Cheese Puffs")
let items = {
"cheesePuffs": {name: "Cheese Puffs",price: 3},
"canOfSoda": {name: "Can of Soda",price: 1.75},
};
console.log("exist: ", items.cheesePuffs!== undefined)
console.log(items.cheesePuffs)
// can also access to item in this way:
console.log(items["cheesePuffs"])
console.log("not exist", items.noCheesePuffs!== undefined)
console.log(items.noCheesePuffs)
Try the following code. It will return you the object where name matches to 'Cheese Puffs'.
let items = [{
name: "Cheese Puffs",
price: 3
},
{
name: "Can of Soda",
price: 1.75
}
];
let itemExist = items.find(x => x.name === 'Cheese Puffs');
if (itemExist) {
console.log(itemExist);
} else {
console.log("Item not Exist");
}
You can use find
let exist = myArrOfObjects.find(o => o.cheesePuffs === 'yes')
First of all you have an array of objects so you can't simply use
myArrOfObjects["cheesePuffs"]
because array required an index so it should be myArrOfObjects[0]["cheesePuffs"]
let items = [
{ name: "Cheese Puffs", price: 3 },
{ name: "Can of Soda", price: 1.75 }
];
let filter = items.find( el => el.price === 3 );
console.log(filter);
another approach
let items = [
{ name: "Cheese Puffs", price: 3 },
{ name: "Can of Soda", price: 1.75 }
];
let filter = items.filter( el => el.price === 3 );
console.log(filter);
Related
let student = [{
id:1,
name:'aman',
class:'10',
gender:'male'
},{
id:2,
name:'shivani',
class:'10',
gender:'female'
},{
id:2,
name:'riyan',
class:'11',
gender:'female'
}]
function customFilter(objList, text){
if(undefined === text || text === '' ) return objList;
return objList.filter(product => {
let flag;
for(let prop in product){
if(product[prop].toString().indexOf(text)>-1){
product[prop] = 0
product[prop]++
flag = product[prop]
console.log(flag)
}
}
return flag;
});}
console.log( customFilter(student, '10'))
I want the output of the number of students in a class. Example: when I pass class 10 as an argument then i should get output how many students in class 10
output:
{class:10,stduent:5 }
I didn't get your question well, but I assumed you want number of student in a class like this {class:10, students: 2}
let student = [
{ id:1, name:'aman', class:'10', gender:'male'},
{ id:2, name:'shivani', class:'10', gender:'female' },
{ id:3, name:'riyan', class:'11', gender:'female' }
]
function customFilter(objList, text){
if(undefined === text || text === '' ) return objList;
const numberOfStudents = objList.filter(product => {
for (let prop in product) {
if (product[prop].toString().includes(text)) {
return true;
}
}
});
return {class:text, student:numberOfStudents.length }
}
console.log( customFilter(student, '10'))
If that's the case this code will do , hope it helps
This would also work:
let students = [
{ id: 1, name: "aman", class: "10", gender: "male" },
{ id: 2, name: "shivani", class: "10", gender: "female" },
{ id: 2, name: "riyan", class: "11", gender: "female" },
];
const customFilter = (students, key, value) => {
const res = { [key]: value, student: 0 };
students.forEach((student) => {
if (student[key] === value) {
res.student += 1;
}
});
return res;
};
console.log(customFilter(students, "class", "10"));
Using Array.prototype.forEach()
There are few problems with the code. change class:'10' to grade: 10,.
don't use "class" as a variable name. might cause a few errors
There is a missing ,
numbers shouldn't be inside quotes because the number will be stored as a string
let student = [
{ id: 1, name: 'aman', grade: 10, gender: 'male'},
{ id: 2, name: 'shivani', grade: 10, gender: 'female' },
{ id: 2, name: 'riyan', grade: 11, gender: 'female' },
]
function customFilter(objList, value){
if(!value || value === '') return objList;
let count = 0
objList.forEach(obj => {
const { grade } = obj;
if(grade === value){
count++;
}
})
return {grade: 10, count};
}
console.log(customFilter(student, 10));
and forEach can be used instead of filter. It loops from start to end of an array
Use .reduce() to group all objects that match.
/* hits (accumulator) is initially an empty array.
now (current) is the object of the current iteration. */
array.reduce((hits, now) => { //...
On each iteration, get all of the current object's values (in lower case) in an array.
Object.values(now).map(val => val.toLowerCase())
/* result of the first object: ["01gn3z1ryjjqhn588ax3bws6qb", "theo bramstom",
"genderqueer", "english"] */
If any of the values of the current object matches the given string (term), add the current object to the hits array.
if (Object.values(now)
.map(val => val.toLowerCase()).includes(term.toLowerCase())) {
hits.push(now);
}
An object literal is returned.
{
"matches": /* an array of all matched objects */,
"total": /* the .length of "matches" array */
};
/* To get the answer prompted in OP -- do the following */
const x = dataFilter(students, "Math");
console.log(x.total);
// NOTE: key "class" is now "subject" just for aesthetics
const students=[{id:"01GN3Z1RYJJQHN588AX3BWS6QB",name:"Theo Bramstom",gender:"Genderqueer",subject:"English"},{id:"01GN3Z1RYM527HAX56ZN14F0YB",name:"Juli Marsy",gender:"Female",subject:"History"},{id:"01GN3Z1RYPYP1FFFEY55T92VX2",name:"Linc Espley",gender:"Non-binary",subject:"Math"},{id:"01GN3Z1RYR325M0QETVVPE2N5J",name:"Barbabas Grisley",gender:"Male",subject:"Math"},{id:"01GN3Z1RYTXA49SBQYXR9DMC04",name:"Godfree Braybrook",gender:"Male",subject:"English"},{id:"01GN3Z1RYVE4N5D16C8QWB1XGF",name:"Jason De Vuyst",gender:"Male",subject:"History"},{id:"01GN3Z1RYXY9WXF1Y407HXFYH8",name:"Adler McCanny",gender:"Male",subject:"Math"},{id:"01GN3Z1RYY9XV444J0SP5Y0QC2",name:"Noellyn MacMorland",gender:"Genderqueer",subject:"Math"},{id:"01GN3Z1RZ0HPQNZ1VKX8ZHA9ZY",name:"Padget Geldeford",gender:"Male",subject:"Math"},
{id:"01GN3Z1RZ2DZE92NG42KSGDXN9",name:"Milissent Treby",gender:"Female",subject:"Art"}];
const dataFilter = (array, term) => {
let result = array.reduce((hits, now) => {
if (Object.values(now).map(val => val.toLowerCase()).includes(term.toLowerCase())) {
hits.push(now);
}
return hits;
}, []);
return {"matches": result, "total": result.length};
}
console.log(dataFilter(students, "Math"));
// Control case: term === "Math"
console.log(dataFilter(students, "PE"));
// No match case: term != "PE"
console.log(dataFilter(students, "female"));
// Case insensitive case: term === "Female"
This question already has answers here:
Move an array element from one array position to another
(44 answers)
Closed 2 years ago.
I have an array of objects with this format
let arr = [ { name: "test1", id: 5}, { name: "test2", id: 6 } , { name: "test3", id: 8 } ]
Now I basically want to move the item with 6 to the front of the array by re-arranging so that result becomes
let result = [ { name: "test2", id: 6 } , { name: "test1", id: 5}, { name: "test3", id: 8 } ]
What I have tried
const found = arr.find((element) => {
return element.id === 6;
});
if (found) {
const [...arr, found] = arr;
return found;
} else {
return arr;
}
You can make use of Array.unshift and Array.splice.
let arr = [{name:"test1",id:5},{name:"test2",id:6},{name:"test3",id:8}]
const moveToFront = (data, matchingId) => {
//find the index of the element in the array
const index = data.findIndex(({id}) => id === matchingId);
if(index !== -1) {
//if the matching element is found,
const updatedData = [...data];
//then remove that element and use `unshift`
updatedData.unshift(...updatedData.splice(index, 1));
return updatedData;
}
//if the matching element is not found, then return the same array
return data;
}
console.log(moveToFront(arr, 6));
.as-console-wrapper {
max-height: 100% !important;
}
You could sort the array with the delta of the checks.
const
array = [{ name: "test1", id: 5 }, { name: "test2", id: 6 }, { name: "test3", id: 8 }];
array.sort((a, b) => (b.id === 6) - (a.id === 6));
console.log(array);
const array = [{ name: "test1", id: 5 }, { name: "test2", id: 6 }, { name: "test3", id: 8 }];
const sortedArray = array.sort((a, b) => (b.id === 6) - (a.id === 6)); console.log(sortedArray);
discusses an easy way to sort your JavaScript Array by the order of the index number for each item in the Array object. This can be helpful if you want to sort alphabetically and not need to create a new String Array with a function like String.sort().
A quick tip that can be useful to you if you want a quick solution to sorting an Array in JavaScript is below.Remember that it is always best practice to use the Array methods built into the language. They are created to work fast and efficient. However, if you really want to sort your array by index number and not have an array of strings, then this article will be for you.:
String→Number: When a function returns a Number value, then JavaScript interprets it as being equal to the Number value in the code...The function is used by passing two parameters, which should return true when they are equal and false when they are not equal.In this case, we are sort of reverse comparing them. We are checking the ID of the items inside the Array to see if they match, but we subtract one to check if they are less than. This is because when we call .sort(), JavaScript is sorting alphabetically and an ID with a value of 6 will be at the end of the list. So, a value of -1 will make it appear in the correct order.If you want to use this method for your Array, then please add a comment below!
You can use Array.unshift() to add element to the beginning of the array and Array.splice() to remove the array element.
let arr = [ { name: "test1", id: 5}, { name: "test2", id: 6 } , { name: "test3", id: 8 } ]
let result = [...arr];
const index = result.findIndex(e => e.id === 6)
result.unshift(result.splice(index, 1)[0])
console.log(result);
You can make use of filter and unshift
let arr = [{ name: "test1", id: 5 },{ name: "test2", id: 6 },{ name: "test3", id: 8 }];
let firstObject;
let result = arr.filter((value) => {
if (value.id != 6) return value;
firstObject = value;
});
result.unshift(firstObject);
console.log(result);
This 2 arrays have multiple objects that has the the same ID but different dates
const names= [
{id:'1',name:'a',date:'1604616214'},
{id:'1',name:'Angel',date:'1604616215'},
{id:'2',name:'b',date:'2004616214'},
{id:'2',name:'Karen',date:'2004616215'},
{id:'3',name:'a',date:'3004616220'},
{id:'3',name:'Erik',date:'3004616221'}
]
const lastnames= [
{id:'1',lastname:'a',date:'4004616220'},
{id:'1',lastname:'Ferguson',date:'4004616221'},
{id:'2',lastname:'b',date:'5004616220'},
{id:'2',lastname:'Nixon',date:'5004616221'},
{id:'3',lastname:'a',date:'6004616222'},
{id:'3',lastname:'Richard',date:'6004616223'}
]
The data is in moment().unix() to create a number "easy to compare"
I want to create a Third array that merge the 2 arrays and create objects with the same id and the last updated date object.
The output should be something like this
const third = [
{id:'1',name:'Angel',lastname:'Ferguson'},
{id:'2',name:'Karen',lastname:'Nixon'},
{id:'3',name:'Erik',lastname:'Richard'}
]
This is what i got so far, if i updated the arrays it duplicates and i need to have only the last updated object
const third = names.map(t1 => ({...t1, ...lastnames.find(t2 => t2.id === t1.id)}))
I'm going to assume since you have the spread operator and Array.find in your example that you can use ES6, which includes for of and Object.values as you see below.
An object and simple looping is used to reduce the amount of times you're iterating. In your example, for every element in names you're iterating over last names to find one with the same ID. Not only is that not ideal for performance, but it doesn't work because every time you're finding the same element with that ID (the first one with that ID in the array).
const names = [
{ id: "1", name: "a", date: "1604616214" },
{ id: "1", name: "Angel", date: "1604616215" },
{ id: "2", name: "b", date: "2004616214" },
{ id: "2", name: "Karen", date: "2004616215" },
{ id: "3", name: "a", date: "3004616220" },
{ id: "3", name: "Erik", date: "3004616221" },
];
const lastnames = [
{ id: "1", lastname: "a", date: "4004616220" },
{ id: "1", lastname: "Ferguson", date: "4004616221" },
{ id: "2", lastname: "b", date: "5004616220" },
{ id: "2", lastname: "Nixon", date: "5004616221" },
{ id: "3", lastname: "a", date: "6004616222" },
{ id: "3", lastname: "Richard", date: "6004616223" },
];
const profiles = {};
function addToProfiles(arr, profiles) {
for (let obj of arr) {
if (obj.id != null) {
// Inits to an empty object if it's not in the profiles objects
const profile = profiles[obj.id] || {};
profiles[obj.id] = { ...profile, ...obj };
}
}
}
addToProfiles(names, profiles);
addToProfiles(lastnames, profiles);
const third = Object.values(profiles);
The idea is to group the objects by their ids, then merge each group according to the rules, maximizing date for each type of record (name and lastname)
// the input data
const names= [
{id:'1',name:'a',date:'1604616214'},
{id:'1',name:'Angel',date:'1604616215'},
{id:'2',name:'b',date:'2004616214'},
{id:'2',name:'Karen',date:'2004616215'},
{id:'3',name:'a',date:'3004616220'},
{id:'3',name:'Erik',date:'3004616221'}
]
const lastnames= [
{id:'1',lastname:'a',date:'4004616220'},
{id:'1',lastname:'Ferguson',date:'4004616221'},
{id:'2',lastname:'b',date:'5004616220'},
{id:'2',lastname:'Nixon',date:'5004616221'},
{id:'3',lastname:'a',date:'6004616222'},
{id:'3',lastname:'Richard',date:'6004616223'}
]
// make one long array
let allNames = [...names, ...lastnames]
// a simple version of lodash _.groupBy, return an object like this:
// { '1': [ { objects with id==1 }, '2': [ ... and so on ] }
function groupById(array) {
return array.reduce((acc, obj) => {
let id = obj.id
acc[id] = acc[id] || [];
acc[id].push(obj);
return acc;
}, {});
}
// this takes an array of objects and merges according to the OP rule
// pick the maximum date name object and maximum date lastname object
// this sorts and searches twice, which is fine for small groups
function mergeGroup(id, group) {
let sorted = group.slice().sort((a, b) => +a.date < +b.date)
let name = sorted.find(a => a.name).name
let lastname = sorted.find(a => a.lastname).lastname
return {
id,
name,
lastname
}
}
// first group, then merge
let grouped = groupById(allNames)
let ids = Object.keys(grouped)
let results = ids.map(id => {
return mergeGroup(id, grouped[id])
})
console.log(results)
I tried to come up with a solution using filter functions. End result contains the format you wanted. check it out.
const names= [
{id:'1',name:'a',date:'1604616214'},
{id:'1',name:'Angel',date:'1604616215'},
{id:'2',name:'b',date:'2004616214'},
{id:'2',name:'Karen',date:'2004616215'},
{id:'3',name:'a',date:'3004616220'},
{id:'3',name:'Erik',date:'3004616221'}
]
const lastnames= [
{id:'1',lastname:'a',date:'4004616220'},
{id:'1',lastname:'Ferguson',date:'4004616221'},
{id:'2',lastname:'b',date:'5004616220'},
{id:'2',lastname:'Nixon',date:'5004616221'},
{id:'3',lastname:'a',date:'6004616222'},
{id:'3',lastname:'Richard',date:'6004616223'}
]
// filter out last updated objects from both arrays
var lastUpdatednames = names.filter(filterLastUpdate,names);
console.log(lastUpdatednames);
var lastUpdatedsurnames = lastnames.filter(filterLastUpdate,lastnames);
console.log(lastUpdatedsurnames);
// combine the properties of objects from both arrays within filter function.
const third = lastUpdatednames.filter(Combine,lastUpdatedsurnames);
console.log(third);
function filterLastUpdate(arrayElement)
{
var max = this.filter( i => arrayElement.id==i.id ).reduce(
function(prev, current)
{
return (prev.date > current.date) ? prev : current
}
)
return max.date == arrayElement.date ;
}
function Combine(firstArray)
{
var subList= this.filter( i => firstArray.id==i.id );
//console.log(subList);
//console.log(subList[0]);
if (subList)
{
firstArray.lastname = subList[0].lastname;
return true;
}
return false ;
}
Here is last output:
[…]
0: {…}
date: "1604616215"
id: "1"
lastname: "Ferguson"
name: "Angel"
1: {…}
date: "2004616215"
id: "2"
lastname: "Nixon"
name: "Karen"
2: {…}
date: "3004616221"
id: "3"
lastname: "Richard"
name: "Erik"
I have a function that interacts with 2 arrays, 1st array is an array of objects that contain my dropdown options, second array is an array of values. I'm trying to filter the 1st array to return what has matched the values in my 2nd array. How do I achieve this?
1st Array:
const books = [
{
label: "To Kill a Mockingbird",
value: 1
},
{
label: "1984",
value: 2
},
{
label: "The Lord of the Rings",
value: 3
},
{
label: "The Great Gatsby",
value: 4
}
]
Code Snippet below:
const idString = "1,2,3";
function getSelectedOption(idString, books) {
const ids = idString.split(",");
const selectedOptions = [];
ids.map(e => {
const selected = books.map(options => {
if (options.value === e){
return {
label: options.label,
value: options.value
}
}
})
selectedOptions.push(selected)
})
return selectedOptions
}
Result:
[
[undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined]
]
Expected Result:
[
{
label: "To Kill a Mockingbird",
value: 1
},
{
label: "1984",
value: 2
},
{
label: "The Lord of the Rings",
value: 3
}
]
Assuming that value is unique, you can update your code as following to get them in order.
const idString = "1,2,3";
function getSelectedOption(idString, books) {
const ids = idString.split(",");
return ids.map(id => books.find(book => book.value == id)).filter(Boolean)
}
You can also filter the books array if you don't care about the order or in case that the value is not unique.
const idString = "1,2,3";
function getSelectedOption(idString, books) {
const ids = idString.split(",");
return books.filter(book => ids.includes(book.value.toString()))
}
Please note that these are O(n*m) algorithms and it should not be used with large sets of data, however if one of the arrays is relatively small you can use it.
function getSelectedOption(idString, books) {
const idArray = convertStringToArray(idString)
return books.filter(item => idString.includes(item.value))
}
function convertStringToArray(string) {
return string.split(",")
}
Using an array filter:
function getSelectedOption(idString, books) {
const ids = idString.split(",");
return books.filter((item) => ids.includes(item.value.toString()));
}
const books = [{
label: "To Kill a Mockingbird",
value: 1
},
{
label: "1984",
value: 2
},
{
label: "The Lord of the Rings",
value: 3
},
{
label: "The Great Gatsby",
value: 4
}
]
const idString = "1,2,3";
getSelectedOption(idString, books);
console.log(getSelectedOption(idString, books));
Some fixes to your solution
After split idString, it would result in array of string value, so you have to cast it to number
Instead of use map to get selected, you should use find
const books = [
{
label: 'To Kill a Mockingbird',
value: 1
},
{
label: '1984',
value: 2
},
{
label: 'The Lord of the Rings',
value: 3
},
{
label: 'The Great Gatsby',
value: 4
}
]
const idString = '1,2,3'
function getSelectedOption(idString, books) {
const ids = idString.split(',').map(Number)
const selectedOptions = []
ids.forEach(e => {
const selected = books
.map(options => {
if (options.value === e) {
return {
label: options.label,
value: options.value
}
}
})
.filter(options => options !== undefined)
selectedOptions.push(selected[0])
})
return selectedOptions
}
console.log(getSelectedOption(idString, books))
i want to access the id 'qwsa221' without using array index but am only able to reach and output all of the array elements not a specific element.
i have tried using filter but couldnt figure out how to use it properly.
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Use Object.keys() to get all the keys of the object and check the values in the array elements using . notation
let lists = {
def453ed: [{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Object.keys(lists).forEach(function(e) {
lists[e].forEach(function(x) {
if (x.id == 'qwsa221')
console.log(x)
})
})
You can use Object.Keys method to iterate through all of the keys present.
You can also use filter, if there are multiple existence of id qwsa221
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
let l = Object.keys(lists)
.map(d => lists[d]
.find(el => el.id === "qwsa221"))
console.log(l)
you can do it like this, using find
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
console.log(
lists.def453ed // first get the array
.find( // find return the first entry where the callback returns true
el => el.id === "qwsa221"
)
)
here's a corrected version of your filter :
let lists = {def453ed: [{id: "qwsa221",name: "Mind"},{id: "jwkh245",name: "Space"}]};
// what you've done
const badResult = lists.def453ed.filter(id => id === "qwsa221");
/*
here id is the whole object
{
id: "qwsa221",
name: "Mind"
}
*/
console.log(badResult)
// the correct way
const goodResult = lists.def453ed.filter(el => el.id === "qwsa221");
console.log(goodResult)
// filter returns an array so you need to actually get the first entry
console.log(goodResult[0])