Adding new property using forEach in an array of objects - javascript-objects

I have 2 arrays of objects. I would like to add a category property to each object in values, example: 50 should fall in the range 41 to 70
let values = [
{1: 124},
{2: 50},
{3: 65},
{4: 21}
];
let categories = [
{cat: "Category1", min: 5, max: 40},
{cat: "Category2", min: 41, max: 70},
{cat: "Category3", min: 71, max: 130}
];
How do I get my result as, using array method forEach():
[
{1: 124, category: "Category3"},
{2: 50, category: "Category2"},
{3: 65, category: "Category2"},
{4: 21, category: "Category1"}
]

Not an optimized one but satisfies the requirement.
let result = [];
values.forEach(element => {
categories.forEach(col => {
let current = Object.values(element)[0];
if(current >= col.min && current <=col.max){
element["category"] = col.cat;
}
})
result.push(element);
})

Related

How to filter array object from another array object?

I want to make another array object from an array object, suppose I fetched a huge data from an api but I need only particular elements from that object. Exampl:-
const mainArray = [
{id: 1, name: 'John', age: 10},
{id: 2, name: 'Mark', age: 14},
{id: 3, name: 'Kevin', age: 15},
{id: 4, name: 'Julie', age: 16},
{id: 5, name: 'Liz', age: 10},
{id: 5, name: 'Emma', age: 11},
{id: 6, name: 'Robert', age: 13},
]
So suppose we have a huge list now I only want Kevin, Emma & Mark to display, for that I need an array of them like this:-
const specialKids = [
{id: 2, name: 'Mark', age: 14},
{id: 3, name: 'Kevin', age: 15},
{id: 5, name: 'Emma', age: 11},
]
How can I achieve that ?
To do this you can use the filter method of JS.
Documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?retiredLocale=de
in your case something like this should be enough:
let specialKids[];
specialKids = mainArray.filter(item => item.name === "Mark" || item.name === "Kevin" || item.name === "Emma")
ArrayList<String> yourintList = new ArrayList<>(Arrays.asList(yourArray));
for (int i = 0; i < yourintList.lenght; i++) {
if (yourintList.contains("Kevin")) {
do something
}

Merge 2 array of objects only if key matches

I have 2 array of objects which I want to merge their properties together ONLY IF user from both array matches.
Example Arrays
arr1 = [{ bank: 1, user: 'fred', depositAmount: 100, withdrawalAmount: 0 }];
arr2 = [{ user: 'fred', gender: 'male', age: 27, state: "arizona" }, { user: 'john',gender: 'male', age: 28, state: "texas" }];
Expected Output
arr1 = [{ bank: 1, user: 'fred', depositAmount: 100, withdrawalAmount: 0, gender: 'male', age: 27, state: "arizona" }];
Here's what I tried so far, but it is returning an empty array
var result = [];
arr1.concat(arr2)
.forEach(item =>
result[item.user] =
Object.assign({}, result[item.user], item)
);
result = result.filter(r => r);
console.log(result)
You can achieve taht by using map, filter Array functionalities and spread operator (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax):
const arr1 = [{ bank: 1, user: 'fred', depositAmount: 100, withdrawalAmount: 0 }, { user: 'john2',gender: 'male', age: 28, state: "texas" }];
const arr2 = [{ user: 'fred', gender: 'male', age: 27, state: "arizona" }, { user: 'john',gender: 'male', age: 28, state: "texas" }];
const newArray = arr1.map((obj) => {
const secondArrayObj = arr2.find((obj2) => obj2.user === obj.user);
if (secondArrayObj) {
return {...secondArrayObj, ...obj}
}
return null;
}).filter((obj) => obj != null);
console.log(newArray);
//[{
// "user": "fred",
// "gender": "male",
// "age": 27,
// "state": "arizona",
// "bank": 1,
// "depositAmount": 100,
// "withdrawalAmount": 0
//}]
Notice that if you have same field in both objects, field from arr2 object will be overridden by field from arr1 object

using array.map to use key of object array of array in typescript

is there anyway I can use array.map to apply a function that parameter is key of array.object in typescript?
I have one object array inside of array. the object with key min and max. I would like to do something like someArrayFunction(array.map(func1(key), array.map())) so I can compare the value from each key of object array
const allVariables: any[] = [
[ { name: 'a', value:{min: 1, max: 2}, expect: {min: 1, max: 2}}, { name: 'b', value: {min: 11, max: 22}, expect: {min:11, max: 22} }],
[ { name: 'a1',value:{min: 1, max: 2}, expect: {min: 1, max: 2}}, {name: 'b1', value: {min: 11, max: 22}, expect: {min:11, max: 22} }],
[ { name: 'a2',value:{min: 1, max: 2}, expect: {min: 1, max: 2}}, {name: 'b2', value: {min: 11, max: 22}, expect: {min:11, max: 22} }],
];
allVariables.forEach(obj => {
Object.keys(obj).forEach((key) => {
// someArrayFunction(someFunc(obj.name, key), obj.value[key])
// so to compare value.min === expect.min from name a
// so to compare value.min === expect.min from name b
// so to compare value.min === expect.min from name a1
// so to compare value.min === expect.min from name b1
// so to compare value.min === expect.min from name c1
// so to compare value.min === expect.min from name c1
})
})
// someArrayFunction(parameter: string[], v: number){
// do something with parameter and v...
// }
I don't know exactly if you wanted that.
const allVariables: any[] = [
[
{ name: 'a', value:{min: 1, max: 2}, expect: { min: 1, max: 2 } },
{ name: 'b', value: {min: 11, max: 22}, expect: { min:11, max: 22 } },
],
[
{ name: 'a1',value:{min: 1, max: 2}, expect: { min: 1, max: 2 } },
{ name: 'b1', value: {min: 11, max: 22}, expect: { min:11, max: 22} },
],
[
{ name: 'a2',value:{min: 1, max: 2}, expect: { min: 1, max: 2 } },
{ name: 'b2', value: {min: 11, max: 22}, expect: { min:11, max: 22 } },
],
];
allVariables.forEach(array => {
array.forEach(obj => {
const {value, expect} = obj;
console.log(someArrayFunction(obj, value));
})
})
function someArrayFunction(value, expect) {
return value.min === expect.min;
}

How to get total of numbers in an array from SharePoint list items

I'm creating a spfx web part using Reactjs. I have a function getting an array of items from a SharePoint list that includes a number column of "Hours". I need to get a total for all the hours that have been returned but can't figure out how to calculate that.
I feel like I'm missing something simple but I've run through all kinds of loops and for some reason I can't get it to work. I've verified that I am getting data from the Hours column.
I'll also state the obligatory "I'm new to spfx and react". :) TIA for any help!
private readItem(): void {
this.props.spHttpClient.get(`${this.props.siteUrl}/_api/web/lists/getbytitle('Time Off')/items?$select=Title,Id,Hours`,
SPHttpClient.configurations.v1,
{
headers: {
'Accept': 'application/json;odata=nometadata',
'odata-version': ''
}
}).then((response: SPHttpClientResponse): Promise<ITimeOffItem[]> => {
return response.json();
})
.then((item: ITimeOffItem[]): void => {
console.log(item); //the data is here including Hours
this.setState({
items: item,
hoursTotal: //????How do I get the sum of "Hours" and assign it to a number in state
});
});
}
Create a function to loop through the items and add the hours
function countHours(items) {
if (!items) {
return 0;
}
let total = 0;
for (let i = 0; i < items.length; i++) {
total += items[i].Hours;
}
return total;
}
const item = [
{ Id: 25, Title: "Comp Time", Hours: 6, ID: 25 },
{ Id: 26, Title: "Comp Time", Hours: 5, ID: 26 },
{ Id: 27, Title: "Work from Home", Hours: 3, ID: 27 },
{ Id: 28, Title: "Comp Time", Hours: 7, ID: 28 },
{ Id: 29, Title: "Work from Home", Hours: 8, ID: 29 },
{ Id: 30, Title: "Holiday", Hours: 8, ID: 30 },
{ Id: 31, Title: "Work from Home", Hours: 32, ID: 31 }
];
console.log(countHours(item));
Use it like
this.setState({
items: item,
hoursTotal: countHours(item)
});
you can also use reduce
const item = [
{ Id: 25, Title: "Comp Time", Hours: 6, ID: 25 },
{ Id: 26, Title: "Comp Time", Hours: 5, ID: 26 },
{ Id: 27, Title: "Work from Home", Hours: 3, ID: 27 },
{ Id: 28, Title: "Comp Time", Hours: 7, ID: 28 },
{ Id: 29, Title: "Work from Home", Hours: 8, ID: 29 },
{ Id: 30, Title: "Holiday", Hours: 8, ID: 30 },
{ Id: 31, Title: "Work from Home", Hours: 32, ID: 31 }
];
const sum = item.reduce(function(a, b) { return a + b.Hours; }, 0);
console.log(sum)
It's hard to answer this without knowing what the data structure looks like, but if you are trying to sum an array of numbers you could use reduce.
const hours = [7, 5, 3, 1, 7]
const totalHours = hours.reduce((accumulator, hour) => accumulator + hour)

ruby / sort an array of hashes from a defined index

Having the following array, it defines the sorting :
[300, 450, 345, 23]
And the following array, unsorted :
[
{id: 450, title: 'rand1'},
{id: 23, title: 'rand3'},
{id: 300, title: 'rand0'},
{id: 345, title: 'rand2'},
]
I'd like the first array to be a "rule" to sort my second array (probably by matching the id key).
How can i get achieve this cleanly ?
Naïve approach:
sorter = [300, 450, 345, 23]
input = [
{id: 450, title: 'rand1'},
{id: 23, title: 'rand3'},
{id: 300, title: 'rand0'},
{id: 345, title: 'rand2'},
]
input.sort do |h1, h2|
sorter.index(h1[:id]) <=> sorter.index(h2[:id])
end
#⇒ [
# {:id=>300, :title=>"rand0"},
# {:id=>450, :title=>"rand1"},
# {:id=>345, :title=>"rand2"},
# {:id=>23, :title=>"rand3"}]
or even simper:
input.sort_by { |h| sorter.index(h[:id]) }

Resources