How to do the sum of the values in an object - javascript

//What I'm trying to do is count the sum of the data in this array.
const storage = [
{ data: '1', status: '0' },
{ data: '2', status: '0' },
{ data: '3', status: '0' },
{ data: '4', status: '0' },
{ data: '5', status: '0' },
{ data: '6', status: '0' },
{ data: '7', status: '1' },
];

You can use the reduce here, see more info about reduce
const storage = [{
data: '1',
status: '0'
},
{
data: '2',
status: '0'
},
{
data: '3',
status: '0'
},
{
data: '4',
status: '0'
},
{
data: '5',
status: '0'
},
{
data: '6',
status: '0'
},
{
data: '7',
status: '1'
},
];
const sum = storage.reduce((acc, value) => acc + Number(value.data), 0);
console.log(sum)

Just use a simple loop - no need to get snarled up with reduce.
(Just make sure you coerce the string value to a Number when you're doing the addition.)
const storage=[{data:"1",status:"0"},{data:"2",status:"0"},{data:"3",status:"0"},{data:"4",status:"0"},{data:"5",status:"0"},{data:"6",status:"0"},{data:"7",status:"1"}];
let sum = 0;
for (const obj of storage) {
sum += Number(obj.data);
}
console.log(sum);

Something like this?
const total = storage.map(({data}) => Number(data)).reduce((a,b) => a + b, 0)
So, first, lets get an array of numbers, which is de first part:
storage.map(({data}) => Number(data))
This will get the data by destructuring from each of the elements, or you can write it like so:
storage.map((item) => Number(item.data))
Then we'll reduce the list by adding all the items together:
list.reduce((a,b) => a + b, 0)
This means, start with 0, then foreach element, add it to the result. This will give you the total.

Related

How to use some lodash method to check if one property doesnt match within two arrays using javascript?

i have 2 array of objects like so,
const initial = [
{
id: '1',
value: '1',
},
{
id: '2',
value: '2',
}
]
const current = [
{
id: '1',
value: '3',
},
{
id: '2',
value: '2',
},
]
these two arrays are almost the same.
i want to check if the current array has value different than the initial array with same id.
so if atleast one of the object in current has value different from the initial value then it should return true. if not false.
so in above example current array with id 1 has value 3 which is different from initial value with id '1'.
i was trying to do something like below,
const output = current.filter(item => some(initial, {id: item.id, value: !item.value}))
but this doesnt seem to be the right way. could someone help me with this. thanks.
Using Map and Array#map, save the id-value pairs of initial
Using Array#some, iterate over current to compare
const _isDifferent = (initial = [], current = []) => {
const map = new Map( initial.map(({ id, value }) => ([id, value])) );
return current.some(({ id, value }) => map.get(id) !== value);
}
const
initial = [ { id: '1', value: '1' }, { id: '2', value: '2' } ],
current = [ { id: '1', value: '3' }, { id: '2', value: '2' } ];
console.log( _isDifferent(initial, current) );
Based on your code,we can compare the length to find if it has different value
let checkDiffArray = (arr1,arr2) =>
arr1.filter(a1 => arr2.some(a2 => a2.id === a1.id && a2.value === a1.id)).length != arr2.length
const initial = [
{
id: '1',
value: '1',
},
{
id: '2',
value: '2',
}
]
const current = [
{
id: '1',
value: '3',
},
{
id: '2',
value: '2',
},
]
let checkDiffArray = (arr1,arr2) => arr1.filter(a1 => arr2.some(a2 => a2.id === a1.id && a2.value === a1.id)).length != arr2.length
console.log(checkDiffArray(initial,current))
You can use the differenceWith combined with the isEqual
const initial = [
{ id: '1', value: '1' },
{ id: '2', value: '2' }
]
const current = [
{ id: '1',value: '3' },
{ id: '2',value: '2' },
]
const output = Boolean(_.differenceWith(current, initial, _.isEqual).length);
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Filter array of objects by array of strings

My Object:
const searchFor = ['appInfo', 'questions'];
My Data:
const data = [
{ id: '1', data: 'jobInfo' },
{ id: '2', data: 'appInfo' },
{ id: '3', data: 'documents' },
{ id: '4', data: 'questions' },
];
I am expecting the final result to be:
[
{ id: '2', data: 'appInfo' },
{ id: '4', data: 'questions' },
];
My try was that I can filter with one item with fixed value
const result = Object.keys(searchFor).map((key) => data.filter((obj) => obj.data === key))
I getting array of arrays but I need array of object and more over I not sure if there is any better way to do this.
Thanks in advance :)
You may use Array.prototype.filter() together with Array.prototype.includes():
const searchFor = ['appInfo', 'questions'],
data = [{id:'1',data:'jobInfo'},{id:'2',data:'appInfo'},{id:'3',data:'documents'},{id:'4',data:'questions'},],
result = data.filter(({data:d}) => searchFor.includes(d))
console.log(result)
.as-console-wrapper{min-height:100%;}
You can use the Array methods .filter and .includes (because searchFor is an Array.)
const searchFor = ['appInfo', 'questions'];
const data = [
{ id: '1', data: 'jobInfo' },
{ id: '2', data: 'appInfo' },
{ id: '3', data: 'documents' },
{ id: '4', data: 'questions' },
];
const result = data.filter(item => searchFor.includes(item.data));
console.log(result);
You could take a Map for the key/objects pairs and map the found objects.
const
searchFor = ['appInfo', 'questions'],
data = [{ id: '1', data: 'jobInfo' }, { id: '2', data: 'appInfo' }, { id: '3', data: 'documents' }, { id: '4', data: 'questions' }],
result = searchFor.map(
Map.prototype.get,
new Map(data.map(o => [o.data, o]))
);
console.log(result);
You can do this:
const searchFor = ['appInfo', 'questions'];
const data = [
{ id: '1', data: 'jobInfo' },
{ id: '2', data: 'appInfo' },
{ id: '3', data: 'documents' },
{ id: '4', data: 'questions' },
];
var res = data.filter(i=> searchFor.includes(i.data))
console.log(res)
If you wanna reduce the complexity to O(N), you may consider this:
const searchFor = ['appInfo', 'questions'];
const data = [
{ id: '1', data: 'jobInfo' },
{ id: '2', data: 'appInfo' },
{ id: '3', data: 'documents' },
{ id: '4', data: 'questions' },
];
var hashTable = {};
searchFor.forEach(i=> hashTable[i] = true );
var res = data.filter(i=>{
return hashTable[i.data]
});
console.log(res)
You can use:
const results = data.filter(item => searchFor.includes(item.data)):
console.log(results):
const result = data.filter((rec, id) => {
if (searchFor.indexOf(rec.data) > -1) {
return rec
}
})
console.log(data.filter(element=>{
return searchFor.includes(element.data)
}));
The idea here is you have to take elements of data and then have to filter each element of data after matching with search for object .since search for the object that contains your filter criteria so it has to be nested within external iteration i.e filter method we have passed on data object .

Javascript filter method, Remove all Items with matching values in array

I'm trying to remove all items if they match with array values but it's removing only one item. How can i remove all items with filter method or what is the best way to achieve this.
let data = [
{
id: '1',
title: 'ABC'
},
{
id: '2',
title: 'DEF'
},
{
id: '3',
title: 'GHI'
},
{
id: '4',
title: 'JKL'
},
{
id: '5',
title: 'MNO'
}
]
data = data.filter(post => {
let remove = ['2', '4', '5']
for(let i = 0; i < remove.length; i++) {
return post.id !== remove[i]
}
})
console.log(data)
Thanks
you should return false if you want to remove item from array
let data = [
{
id: '1',
title: 'ABC'
},
{
id: '2',
title: 'DEF'
},
{
id: '3',
title: 'GHI'
},
{
id: '4',
title: 'JKL'
},
{
id: '5',
title: 'MNO'
}
]
let remove = ['2', '4', '5']
data = data.filter(post => {
return !remove.includes(post.id);
})
console.log(data)
All the notice are in the snippet's comment
let data = [ { id: '1', title: 'ABC' }, { id: '2', title: 'DEF' }, { id: '3', title: 'GHI' }, { id: '4', title: 'JKL' }, { id: '5', title: 'MNO' } ]
const remove = ['2', '4', '5']
// `indexOf` is from ES5
data = data.filter(post => remove.indexOf(post.id) === -1)
console.log(data)
// `includes` is from ES7
data = data.filter(post => !remove.includes(post.id))
console.log(data)
// this will recreate the array ['2', '4', '5'] 5 times
data = data.filter(post => !['2', '4', '5'].includes(post.id))
console.log(data)
There is no need to use for loop inside of filter.
Instead it is possible to use some method inside of filter. The some method checks whether at least one element satisfies condition inside of provided function. So unnecessary iteration will be avoided:
data.filter(f => !remove.some(s => s == f.id))
An example:
let data = [
{
id: '1',
title: 'ABC'
},
{
id: '2',
title: 'DEF'
},
{
id: '3',
title: 'GHI'
},
{
id: '4',
title: 'JKL'
},
{
id: '5',
title: 'MNO'
}
]
let remove = ['2', '4', '5']
console.log(data.filter(f => !remove.some(s => s == f.id)));
I'll suggest using includes rather then a nested for loop.
You should also move the remove var outside of the loop, so it's not reinitialised every time.
The callback to the filter method is a predicate. If the condition evaluates to true, the current value in the iteration will be returned. In your case, you want to return if the current value is not in the remove array.
let data = [
{
id: '1',
title: 'ABC'
},
{
id: '2',
title: 'DEF'
},
{
id: '3',
title: 'GHI'
},
{
id: '4',
title: 'JKL'
},
{
id: '5',
title: 'MNO'
}
]
const remove = ['2', '4', '5']
data = data.filter(post => {
return !remove.includes(post.id)
})
console.log(data)

remove duplicates from a randomly selected array

I have the following code which tries to remove duplicates from a randomly selected array items but it did'nt work,
items[] is the array containing its and i have usea sript to remove duplicates.
how do i change it to remove duplicates
what is the mistake?
window.onload = rnumber();
function rnumber() {
const
items = [
{ label: '1', url: '1.jpg' },
{ label: '2', url: '2.jpg' },
{ label: '3', url: '3.jpg' },
{ label: '4', url: '4.jpg' },
{ label: '5', url: '5.jpg' },
{ label: '6', url: '6.jpg' },
{ label: '7', url: '7.jpg' },
{ label: '8', url: '8.jpg' },
{ label: '9', url: '9.jpg' },
{ label: '10',url: '10.jpg' }
];
var lastnumber=0;
for (let index = 0; index < 9; index++)
{
randomIndex = Math.floor(Math.random() * items.length);
if(lastnumber!=randomIndex)
{
item = items[randomIndex];
lastnumber=randomIndex;
console.log(randomIndex);
}
else
{
rnumber()
}
}
}
You can use reduce to get rid of duplicates
const distinctShuffle = array =>
array ? array.reduce((arr, item) => {
if (!(item in arr)) {
arr.splice(Math.floor(Math.random() * (arr.length + 1)), 0, item);
}
return arr;
}, []) : array;
function rnumber() {
const items = [
{ label: '1', url: '1.jpg' },
{ label: '2', url: '2.jpg' },
{ label: '3', url: '3.jpg' },
{ label: '4', url: '4.jpg' },
{ label: '5', url: '5.jpg' },
{ label: '6', url: '6.jpg' },
{ label: '7', url: '7.jpg' },
{ label: '8', url: '8.jpg' },
{ label: '9', url: '9.jpg' },
{ label: '10',url: '10.jpg' }
];
return distinctShuffle(items);
}
console.log(rnumber());
You have some syntax errors in your code. Watch out for using semicolons at the end of the statement - not commas.
If you're using ES6 you can write something like this:
let distinct = [...new Set(items.map(item => item.label))]
Use Following Simple Function to Remove Duplicates from array using jquery
var YourArray = [
{ label: '1', url: '1.jpg' },
{ label: '1', url: '2.jpg' },
{ label: '3', url: '3.jpg' },
{ label: '4', url: '4.jpg' },
{ label: '1', url: '5.jpg' },
{ label: '6', url: '6.jpg' },
{ label: '1', url: '7.jpg' },
{ label: '8', url: '8.jpg' },
{ label: '9', url: '9.jpg' },
{ label: '10',url: '10.jpg' }
];
var SortedArray = YourArray.filter(
function(a){if (!this[a.label]) {this[a.label] = 1; return a;}},
{}
);
alert(JSON.stringify(SortedArray));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Append array into the array of Objects

I have an array of objects as shown below.
var myArray = [
{
Data: '455',
Note: 'tre',
Id: '4'
},
{
Data: '456',
Note: 'bre',
Id: '5'
},
{
Data: '457',
Note: 'cre',
Id: '6'
}
];
I also have this array
Percent = [ '10', '20', '30'],
Can someone please let me know how do i add this array elements into the array of objects. tHe expected output is as follows.
var myArray = [
{
Data: '455',
Note: 'tre',
Id: '4',
Percent: '10'
},
{
Data: '456',
Note: 'bre',
Id: '5',
Percent: '20'
},
{
Data: '457',
Note: 'cre',
Id: '6',
Percent: '30'
}
];
Assuming Percent always contains the same number of items as myArray, loop over myArray and assign the correct value from Percent like this:
myArray.forEach(function(object,index) {
object.Percent = Percent[index];
});
Same assumption as #Adam, but using ES6 arrow function feature:
myArray.map((x,i) => x.Percent = percent[i]);
here is a plunker : link
Don't forget to check browser compatibility : here

Categories