Best way to find smallest value from array containing objects - javascript

I wants to find out the object which holds the smallest value of a key in an array.
var tempArr = [{name: 'john', age: 23}, {name: 'jonny', age: 27}, {name: 'roony', age: 13}, {name: 'david', age: 33}];
I want the result to be
{name: 'roony', age: 13}
without using for loop is there any direct way to find out the result, like we can do for plain array
for example:
if array is -
var arr = [11,4,22,3,5,55];
we can achieve the same by:
Math.min.apply(null, arr)

You should use reduce:
min = tempArr.reduce(function(previousValue, currentValue, index, array) {
return (currentValue.age < previousValue.age ? currentValue : previousValue);
});
Any solution involving sort will be suboptimal.

#antyrat's solution is more explicit, but I figured I'd provide another way:
var people=[{name: 'john', age: 23}, {name: 'jonny', age: 27}, {name: 'roony', age: 13}, {name: 'david', age: 33}];
var youngestPerson=people.reduce(function(youngestPerson,person){
return person.age<youngestPerson.age ? person : youngestPerson;
},people[0]);
console.log(youngestPerson);

Yes, you can use sort method:
var tempArr = [{name: 'john', age: '23'}, {name: 'jonny', age: '27'}, {name: 'roony', age: '13'}, {name: 'david', age: '33'}];
tempArr = tempArr.sort( function( a, b ) {
var AgeA = parseInt( a.age, 10 );
var AgeB = parseInt( b.age, 10 )
if ( AgeA < AgeB ) return -1;
else if ( AgeA > AgeB ) return 1;
else return 0;
});
console.log(tempArr);
console.log(tempArr[0]); // is the record with smallest `age` value

Related

Return array values which are not duplicates

var arr = [
{name:"Grace", age: "28"},
{name:"Peter", age: "15"},
{name:"Grace", age: "28"},
{name:"John", age: "16"},
{name:"Prince", age: "19"},
{name:"John", age: "16"}
];
I now want return only those which are unique as below
var new = [
{name:"Peter", age: "15"},
{name:"Prince", age: "19"},
];
You can use Map and reduce
First create a mapper based on name and count repetition of each name
Select only the values where repetition is exactly 1
const arr = [{name:"Grace", age: "28"},{name:"Peter", age: "15"},{name:"Grace", age: "28"},{name:"John", age: "16"},{name:"Prince", age: "19"},{name:"John", age: "16"}];
let mapper = arr.reduce( (op,inp) => {
let {name:key} = inp
op.set(key, op.get(key) || {value: inp, count:0})
op.get(key).count++
return op
},new Map())
let final = [...mapper.values()].reduce((op,{value,count}) => {
if(count === 1){
op.push(value)
}
return op
},[])
console.log(final)

How can I filter an array of objects with a value from another object?

I want to write a function which takes an array of objects with certain key value pairs as the first argument. And an object with key value pairs as the second argument.
The function should check if the key value pairs from the second argument are found in the array of objects from the first argument.
If so, it should return an array of objects which have the matching name and value pairs.
For example, if I have an array of objects (first argument):
[{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
And as the second argument:
{age: 17}
It should return:
[{name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
Because of the matching value age
This is what I have come up with but don't know what to put in the for...in loop:
function checkTheName(list, check) {
let newArr = [];
for(let i = 0; i < list.length; i++){
for(let key in list[i]){
// Stuck here
}
}
return newArr;
}
You can do this with filter and every methods.
let a = [{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
let b = {age: 17}
function checkTheName(list, check) {
return list.filter(o => Object.keys(check).every(k => {
return (k in o) && check[k] == o[k]
}))
}
console.log(checkTheName(a, b))
A simple ES6 version with Array.prototype.filter and Array.prototype.every:
const data = [{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}];
const fObj = {age: 17};
const filtred = data.filter(item =>
Object.keys(fObj).every(k => item.hasOwnProperty(k) && item[k] === fObj[k])
);
console.log(filtred);
You can loop over the array and test for that property:
function checkTheName(check, list){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
var array =[{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon",
age: 17}, {namenter code heree: "Poopy", age: 17}]
;
var resultObject = checkTheName( array,"string 1");
Use filter to loop over the array.
function findByAge(myArr, obj){
myArr.filter( (item) => {
if(obj.age === item.age){
return item
}
})
}
This will return an array with just the array items that you are looking for.
You can call it following line. Since the function returns a new array. We need to give the new array a name (newArray in this example).
var newArray = findByAge(myArr, obj)
You need to put an if condition comparing the age value of your check object with the age value of the list object. In case, both the values are equal, push object in newArr.
let list = [{ name: "Peter", age: 21 }, { name: "Kate", age: 18 }, { name: "Tihon", age: 17 }, { name: "Poopy", age: 17 }],
check = { age: 17 };
function checkTheName(list, check) {
let newArr = [];
for (let i = 0; i < list.length; i++) {
if (list[i].age == check.age) {
newArr.push(list[i]);
}
}
return newArr;
}
console.log(checkTheName(list, check));
Alternatively, you can also use array#filter.
let list = [{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}],
check = {age: 17},
result = list.filter(o => o.age === check.age);
console.log(result);
var filterobj ={age:17};
var data=[{name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
var newArray = data.filter(function (el) {
return el.age ==filterobj.age;
}

Check if same object exists in an array - Javascript

I have an array of objects as follows
[{name: "jack", age: 10}, {name: "john", age: 15}]
Consider that i have an object
{name: "jack", age: 10}
Now i need to check if this object exist in the array. If all the properties(name, age) of the object matches, then display an alert on the page.
How to accomplish this using pure javascript?
Use Array.some, Array.every and Object.entries
A match will be counted if
There are equal number of keys
There is a match for every key/value pair
var arr = [{name: "jack", age: 10}, {name: "john", age: 15}];
var input = {name: "jack", age: 10};
var result = arr.some((o) => Object.entries(input).every(([k,v]) => o[k] === v) && Object.keys(input).length === Object.keys(o).length);
console.log(result);
Try this:
var data = [{name: "jack", age: 10}, {name: "john", age: 15}];
var input = {name: "jack", age: 10};
for(var i=0;i<data.length;i++)
{
if(data[i].name==input.name && data[i].age == input.age)
{
alert('matched');
break;
}
}
This may be a bad performing method, but it would cover nested object cases with ease. Also this is only suited if ALL key/value pairs must match and that the key/value pairs were defined in the same order.
let c = [{name: "jack", age: 10}, {name: "john", age: 15}],
s = {name: "jack", age: 10};
console.log(c.filter(e => JSON.stringify(s) === JSON.stringify(e)));
You can try this if you don't want to check for index of object inside array object
var obj = [{name: "jack", age: 10}, {name: "john", age: 15}];
var checkObj = {name: "john", age: 15};
if(JSON.stringify(obj).indexOf(JSON.stringify(checkObj)) >= 0){
console.log("Object Available");
}else{
console.log("Object Not Available");
}

Javascript Array add or update

Javascript Array push issue
I have a object:
people: [{name: peter, age: 27, email:'peter#abc.com'}]
I want to push:
people.push({
name: 'John',
age: 13,
email: 'john#abc.com'
});
people.push({
name: 'peter',
age: 36,
email: 'peter#abc.com'
});
The finally I want is:
people: [
{name: 'peter', age: 36, email:'peter#abc.com'},
{name: 'john', age: 13, email:'john#abc.com'},
]
I dont have any key but the email is a unique
You can also do like this by generating an Array method. It takes two arguments. First one designates the object to push and the second is the unique property to check to replace if a previously inserted item exists.
var people = [{name: 'peter', age: 27, email:'peter#abc.com'}];
Array.prototype.pushWithReplace = function(o,k){
var fi = this.findIndex(f => f[k] === o[k]);
fi != -1 ? this.splice(fi,1,o) : this.push(o);
return this;
};
people.pushWithReplace({name: 'John', age: 13, email: 'john#abc.com'}, "email");
people.pushWithReplace({name: 'peter', age: 36, email: 'peter#abc.com'},"email");
console.log(people);
There is no "update" method as is in JavaScript.
What you have to do, is simply looping through your array first to check if the object is already inside.
function AddOrUpdatePeople(people, person){
for(var i = 0; i< people.length; i++){
if (people[i].email == person.email){
people[i].name = person.name;
people[i].age = person.age;
return; //entry found, let's leave the function now
}
}
people.push(person); //entry not found, lets append the person at the end of the array.
}

Merge Array of Objects

I need to merge arrays of objects in browserside javascript like this:
[
{name: "john", age: 10},
{name: "doe", age: 14}
]
--> new data arrives
[
{name: "pete", age: 88},
{name: "larry", age: 42}
]
should become
[
{name: "john", age: 10},
{name: "doe", age: 14},
{name: "pete", age: 88},
{name: "larry", age: 42}
]
Well thats simplified the arrays will contain hundreds of larger objects. Therefore I need a performant solution.
Thanks in advance yours skeec
It seems you can just use .push() or .concat() to combine the two arrays. It does not matter what is in the arrays as the array operators just work on the elements of the array abstractly without knowing what's in them.
Here's a solution that adds the new array onto the existing one:
var data = [
{name: "john", age: 10},
{name: "doe", age: 14}
];
var newInfo = [
{name: "pete", age: 88},
{name: "larry", age: 42}
]
data = data.concat(newInfo);
Or, if you really want to keep the original array (not create a new one), you can add the new array onto the end of the original array like this:
data.push.apply(data, newInfo);
Assuming you don't need anything other than just concatenating the 2 arrays, it's supremely simple, since arrays have a method for concatenation already.
var arr1 = [
{name: "pete", age: 88},
{name: "larry", age: 42}
];
var arr2 = [
{name: "pete", age: 88},
{name: "larry", age: 42}
];
var concatArr = arr1.concat(arr2);
MDN Page on Array.prototype.concat
var arr3 = [];
for(var i in arr1){
var shared = false;
for (var j in arr2)
if (arr2[j].name == arr1[i].name) {
shared = true;
break;
}
if(!shared) arr3.push(arr1[i])
}
arr3 = arr3.concat(arr2);
You can use loadash for that:
Something like this:
var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
console.log(other);
// → [1, 2, 3, [4]]
console.log(array);
// → [1]
Or for Json you can use extend like this:
lodash.extend({}, mergeInto, toMerge)

Categories

Resources