Check if an array of objects contains another object [duplicate] - javascript

This question already has answers here:
Javascript: Using `.includes` to find if an array of objects contains a specific object
(7 answers)
How to determine equality for two JavaScript objects?
(82 answers)
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Closed 2 years ago.
I have this code:
const arr = [
{name:"Bill", age:11},
{name:"Bill", age:11}
]
console.log(arr.includes({name:"Bill", age:11}))
Here i want to check if the array includes {name:"Bill", age:11}.
Why i get false? And how to make this checking using includes?

The includes() method compares objects by reference and not by value. In your case the three objects have three different references although they have the same properties and the same values in them.
const bill = { name: 'Bill', age: 11 }
const arr = [bill, { name: 'Jane', age: 18 }]
arr.includes(bill) // true (same reference)
arr.includes({ name: 'Bill', age: 11 }) // false (different reference)
If you want to find objects by value, you can use the find() method and pass a filter function which checks if each property of the object matches your criteria.
const arr = [{name:"Bill", age:11}, {name:"Jane", age:18}]
const exists = Boolean(arr.find(x => x.name === 'Bill' && x.age === 11))
// or even simpler using the `some()` method
const exists = arr.some(x => x.name === 'Bill' && x.age === 11)

You can create a custom array prototype method for this like includesObj
const arr = [
{name:"Bill", age:11},
{name:"Bill", age:11}
]
Array.prototype.includesObj = function(obj) {
for(let i = 0; i < this.length; i++) {
if(JSON.stringify(this[i], Object.keys(this[i]).sort()) === JSON.stringify(obj, Object.keys(obj).sort())) return true;
}
return false;
}
console.log(arr.includesObj({name: "Bill", age: 11}))
console.log(arr.includesObj({age: 11, name: "Bill"}))
console.log(arr.includesObj({name: "Bob", age: 11}))

Related

How to get an array of a specific property of an object from an array of objects using filter() in Javascript? [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 2 years ago.
I am trying to learn Javascript specifically the method, "filter()". I want to get an array of names from an array of objects. It just returns the same array of objects passed as an argument. What am I missing?
Update: I confused filter() with map(). I am sorry to waste people's time.
personsObj = {
persons: [{name: "Baig",age: 14},{name: "HenTie", age: 20}]
}
switchButtonHandler = (personsArray) => {
var names = this.personsArray.persons.filter((obj) => obj.name);
console.log(names);
}
No, what you are trying to do is map an array to an array of other thing. In your case:
const personsArray = {
persons: [{name: "Baig",age: 14},{name: "HenTie", age: 20}]
}
const newArray = personsArray.persons.map(person => person.name) // use proper name
console.log(newArray)
Map is intended to transform an array into other different array and filter is intended to return an array based on a condition, like in this case "give me all the people with age higher than 18", so you could do:
const personsArray = {
persons: [{name: "Baig",age: 14},{name: "HenTie", age: 20}]
}
const adults = personsArray.persons.filter(person => person.age > 18)
console.log(adults)

Is There Any Method To Push Object To Array Uniquely? [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 4 years ago.
Is there any method to push object to array uniquely with 1 method by ES6 ?
For Ex:
MyArray.pushUniquely(x);
Or good to use old version like ? :
MyMethod(x) {
if ( MyArray.IndexOf(x) === -1 )
MyArray.Push(x);
}
Is there any method to push uniquely by ES6 ?
Use a Set collection instead of an array.
var mySet = new Set([1, 2, 3]);
mySet.add(4);
mySet.add(3);
mySet.add(0)
console.log(Array.from(mySet))
Use includes (I've made an extension of a method so you can use it on all arrays):
Array.prototype.pushUnique(item) {
if (!this.includes(item)) this.push(item);
}
Alternatively, use a Set:
mySet.add(x); //Will only run if x is not in the Set
You can use lodash uniq method.
var uniq = _.uniq([1,2,3,4,5,3,2,4,5,1])
console.log(uniq)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
If the array is an array of objects you can do
const arr = [{
name: 'Robert',
age: 26
},
{
name: 'Joshua',
age: 69
}
]
Array.prototype.pushUniquely = function (item) {
const key = 'name';
const index = this.findIndex(i => i[key] === item[key]);
if (index === -1) this.push(item);
}
arr.pushUniquely({
name: 'Robert',
age: 24
});
console.log(arr);
If it's just an array of string or number then you can do:
Array.prototype.pushUniquely = function (item) {
if (!this.includes(item)) this.push(item);
}

JavaScript filtering array full of objects [duplicate]

This question already has answers here:
Get JavaScript object from array of objects by value of property [duplicate]
(17 answers)
Closed 5 years ago.
I am having trouble with some basic javascript. I want this function to return an array of all objects within the given array that have the name "Ray" assigned to name. I can't get the push part to work.
const people = [{name: "Jack", age: 30}, {name: "Ray", age: 32}, {name: "Anna", age: 28}];
function findRay(arr) {
let response = [];
for(let i = 0; i < arr.length; i++) {
if(arr[i].name === "Ray") {
response.push(arr[i]);
}
}
return response;
}
console.log(findRay(people));
While not exactly what you were looking for, this is a good use case for filter(). So you could do something like const findRay = arr => arr.filter(person => person.name === "Ray").

Javascript: How do I access an individual object in an object array, given one of the key's value's, without using a for loop? Is that possible? [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 7 years ago.
An object with an array of objects, and a function that returns all the names of each object in the array. This works.
var persArr = {friends:[
{name: "Adam", age: 37},
{name: "Ben", age: 36},
{name: "Chris", age: 46}],
getFriend:function(){
return this.friends.map(function(friend){
return friend.name;
}).join(', ').slice();
}};
var names = persArr.getFriend();
console.log(names);
How can I return a name and age property of an object, based on search criteria?
example: {name:"Chris", age:46},
{name:"Ben",age: "36"}
perArr.getFriend("Chris");
Just change your return function to return an object. Something like:
getFriend:function(name){
return this.friends.filter(function(friend){
if(friend.name===name){
return {name:friend.name, age:friend.age};}
});
}};
var nameAge = persArr.getFriend('Adam');
console.log(nameAge);
Could change your function to use filter() instead of map:
getFriend:function(name){
var match = this.friends.filter(function(friend){
return friend.name === name;
});
return match.length ? match[0] : false;
}};
You can iterate over the list and check if the name matches your search parameter.
If it matches return the actual object.
In case it doesn't find anything return undefined.
getFriend: function(name) {
for (var i = 0; i < friends.length; i++) {
if (friends[i].name == name) {
return friends[i];
}
}
return undefined;
}

Javascript: How to find key name in array of objects [duplicate]

This question already has answers here:
How to check if object property exists with a variable holding the property name?
(11 answers)
Closed 7 years ago.
I am trying to determine if a key name is present in my array of object. As an example, how would I verify if the key with a name of 'name' equals the argument passed in my function call? Below is code to further clarify.
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var test = function(arr, propName){
var result = [];
for(var i = 0; i < arr.length; i++){
if(arr[i][propName] === propName){
result.push(arr[i][propName]);
}
}
return result;
}
func(stooges, "name");
Using underscore.js:
var names = _.pluck(stooges, 'name');
In fact this is the very example given on their page?!
So, on the basis that you knew this, but want to know how to write something similar:
function pluck(array, prop]) {
return array.map(function(entry) {
return entry[prop];
});
}
or more safely, returning an empty array if the initial array is undefined:
function pluck(array, prop]) {
return array ? array.map(function(entry) {
return entry[prop];
}) : [];
}

Categories

Resources