Get ID of highest property [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How can I return the ID with the highest 'number' associated with it?
items = [
{id: 4, number: 45},
{id: 5, number: 49},
{id: 7, number: 44}
]

You can combine find and every()
const items = [
{id: 4, number: 45},
{id: 5, number: 49},
{id: 7, number: 44}
]
const res = items.find(x => items.every(a => a.number <= x.number)).id
console.log(res)
const items = [
{id: 4, number: 45},
{id: 5, number: 49},
{id: 7, number: 44}
]
const res = items.sort((a,b) => b.number - a.number)[0].id
console.log(res)
The above solution has O(n ^ 2) time complexity. If you want linear time complexity you can first find max number using Math.max and then use find
const items = [
{id: 4, number: 45},
{id: 5, number: 49},
{id: 7, number: 44}
]
const max = Math.max(...items.map(x => x.number));
const res = items.find(x => x.number === max).id;
console.log(res)

you can use reduce
const items = [
{id: 4, number: 45},
{id: 5, number: 49},
{id: 7, number: 44}
]
const max = items.reduce((max , item) => {
if(max.number < item.number){
return item;
}
return max;
});
console.log(max.id);

Both approaches require only a single loop to obtain the desired object(s).
If the data contains only one max number, then you could reduce th array and take only the one object with the greater number.
const
items = [{ id: 4, number: 45 }, { id: 5, number: 49 }, { id: 7, number: 44 }],
maxItem = items.reduce((a, b) => a.number > b.number ? a : b);
console.log(maxItem.id);
Approach for having more than one item with max number.
const
items = [{ id: 4, number: 45 }, { id: 5, number: 49 }, { id: 6, number: 49 }, { id: 7, number: 44 }],
maxItems = items.reduce((max, item, i) => {
if (!i || max[0].number < item.number) return [item];
if (max[0].number === item.number) max.push(item);
return max;
}, []);
console.log(maxItems);

Related

How to check with an array have some values

How to verify with i have only 2 or 3 numbers inside this?
without this ----> if(Array.includes(1) && !Array.includes(3))
const servicesTest: IServices[] = [
{
id: '1',
name: 'Hair',
price: 25,
icon: 'https://cdn-icons-png.flaticon.com/512/7478/7478480.png'
},
{
id: '2',
name: 'Beard',
price: 20,
icon: 'https://cdn-icons-png.flaticon.com/512/7578/7578754.png'
},
{
id: '3',
name: 'Eyebrow',
price: 15,
icon: 'https://cdn-icons-png.flaticon.com/512/2821/2821012.png'
}
]
if the client choose hair + beard this will be 40 not 45.
I´m doing this:
const name = findServices.map(services => services.name)
if (name.includes('Hair') && name.includes('Beard') && !name.includes('Eyebrown')) {
return (
setTotalDay(prevState => prevState + 40),
setTotalMonth(prevState => prevState + 40)
)
}
I would create an array of discounts like this:
const discounts = [{
price: 30,
ids: [1, 2],
}];
Then check if the array has only discounted items like this:
array.length === discount.ids.length && array.every((item) => discount.ids.includes(item.id))
const discounts = [{
price: 30,
ids: [1, 2],
}];
const discounted = [{
id: 1,
name: 'Hair',
price: 20,
},
{
id: 2,
name: 'Beard',
price: 30,
},
];
const fullPrice = [{
id: 1,
name: 'Hair',
price: 20,
},
{
id: 2,
name: 'Beard',
price: 30,
},
{
id: 3,
name: 'Tea',
price: 30,
},
];
console.log("discounted", getTotal(discounted));
console.log("full price", getTotal(fullPrice));
function getTotal(array) {
for (const discount of discounts) {
if (
array.length === discount.ids.length &&
array.every((item) => discount.ids.includes(item.id))
) {
return discount.price;
}
}
return array.reduce((sum, item) => sum + item.price, 0);
}
answering your question before the edit.
Assuming we have this array
const Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Let's say we want to check if values 2 and 3 exist.
We store the values in an array let toCheck = [2,3];
We can use function every to loop all the elements of toCheck array against the Array const
Example Follows:
const Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let toCheck = [1,2];
const allExist = toCheck.every(value => {
return Array.includes(value);
});
Hope it helps.

Filtering using two array of objects using JavaScript

I have an array as shown:
var arrOne = [{id: 3},{id: 8},{id: 12}];
And another array as shown:
var arrTwo = [
{id: 1, val: 'Adam'},
{id: 3, val: 'Bailey'},
{id: 8, val: 'Cathy'},
{id: 12, val: 'David'},
{id: 15, val: 'Earl'}
];
I want to iterate arrTwo based on arrOne, and get the val values out of arrTwo.
So the result should be:
var result = ['Bailey', 'cathy', 'David'];
Tried concatenating .map with .filter:
arrOne.map(arOne => arrTwo.filter(artwo => {
if(arOne.id === artwo.id) {
return artwo.val
} else {
return false;
}
}));
But it gives me all, and where it is false it adds false there, which I don't want.
Any ideas where I am going wrong will be appreciated.
Editing as per norbitrial's answer:
const arrOne = [{id: 3},{id: 8},{id: 12}];
const arrTwo = [
{id: 1, val: 'Adam'},
{id: 3, val: 'Bailey'},
{id: 8, val: 'Cathy'},
{id: 12, val: 'David'},
{id: 15, val: 'Earl'}
];
const result = arrOne.map(({id}) => arrTwo.find(e => {
const someCond = someConditionaEval();
if(someCond && e.id === id) {
return e;
} else {
return false;
}
}).val); //this breaks
Using .map() and .find() combination:
const arrOne = [{id: 3},{id: 8},{id: 12}];
const arrTwo = [{id: 1, val: 'Adam'}, {id: 3, val: 'Bailey'}, {id: 8, val: 'Cathy'}, {id: 12, val: 'David'}, {id: 15, val: 'Earl'}];
const result = arrOne.map(({id}) => arrTwo.find(e => e.id === id).val);
console.log(result);
I hope this helps!
You can use .filter() method on arrTwo and then using .includes() method get the filtered objects from arrTwo and then finally using .map() get only the val property values from each filtered object like:
var arrOne = [{id: 3},{id: 8},{id: 12}];
var arrTwo = [{id:1,val:"Adam"},{id:3,val:"Bailey"},{id:8,val:"Cathy"},{id:12,val:"David"},{id:15,val:"Earl"}];
var result = arrTwo.filter(a => arrOne.map(o=>o.id).includes(a.id)).map(o=>o.val)
console.log( result )
You could take an object with the values and then map the wanted values.
var arrOne = [{ id: 3 }, { id: 8 }, { id: 12 }],
arrTwo = [{ id: 1, val: 'Adam' }, { id: 3, val: 'Bailey' }, { id: 8, val: 'Cathy' }, { id: 12, val: 'David' }, { id: 15, val: 'Earl' }],
values = arrTwo.reduce((r, { id, val }) => (r[id] = val, r), {}),
result = arrOne.map(({ id }) => values[id]);
console.log(result);
Create a Map of val by id from arrTwo, and then map arrOne, and extract the val from the Map using the id.
Why I prefer creating a Map/dictionary (object) instead of using Array.map() with Array.find()?
Because of the complexity - Array.map() with Array.find(), for example, is O(n * m), while creating a Map and then using Array.map() to get the values is O(n + m). However, if you've got two small arrays, this shouldn't actually hurt actual performance.
const arrOne = [{id: 3},{id: 8},{id: 12}];
const arrTwo = [{id: 1, val: 'Adam'}, {id: 3, val: 'Bailey'}, {id: 8, val: 'Cathy'}, {id: 12, val: 'David'}, {id: 15, val: 'Earl'}];
const valById = new Map(arrTwo.map(({ id, val }) => [id, val]));
const result = arrOne.map(o => valById.get(o.id));
console.log(result);
Build an object from arrTwo to gather val's in one iteration.
use map on arrOne and get val from above object.
const update = (arr1, arr2) => {
const all = Object.fromEntries(arr2.map(({ id, val }) => [id, val]));
return arr1.map(({ id }) => all[id]);
};
var arrOne = [{ id: 3 }, { id: 8 }, { id: 12 }];
var arrTwo = [
{ id: 1, val: "Adam" },
{ id: 3, val: "Bailey" },
{ id: 8, val: "Cathy" },
{ id: 12, val: "David" },
{ id: 15, val: "Earl" }
];
console.log(update(arrOne, arrTwo));

ES6 : sorting an array based on another array order [duplicate]

This question already has answers here:
Javascript - sort array based on another array
(26 answers)
Closed 2 years ago.
sortedArray = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]
unSortedArray = [{id: 8, text : 'abcd'}, {id: 4, text : 'ab'}, {id: 1, text : 'cd'}, {id: 2, text : 'def'}, {id: 3, text : 'abcd'}, {id: 5, text : 'abcd'}]
I want to sort unSortedArray based on items of sortedArray and want only object which has same id as in sortedArray
Result expected
[{id: 1, text : 'cd'}, {id: 2, text : 'def'}, {id: 3, text : 'abcd'}, {id: 4, text : 'abc'}]
I have tried similar suggestions based on similar questions.
Adding link of such question here
You could get a hash table first and then map only wanted items.
var sortedArray = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
unSortedArray = [{ id: 8, text : 'abcd' }, { id: 4, text : 'ab' }, { id: 1, text : 'cd' }, { id: 2, text : 'def' }, { id: 3, text : 'abcd' }, { id: 5, text : 'abcd' }],
items = unSortedArray.reduce((r, o) => (r[o.id] = o, r), {}),
result = sortedArray.map(({ id }) => items[id]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this
let sortedArray = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
let unSortedArray = [
{ id: 8, text: "abcd" },
{ id: 4, text: "ab" },
{ id: 1, text: "cd" },
{ id: 2, text: "def" },
{ id: 3, text: "abcd" },
{ id: 5, text: "abcd" }
];
// Method 1 - Reduce
let sorted = sortedArray
.map(itm => itm.id)
.reduce((acc, id) => acc.concat(unSortedArray.filter(itm => itm.id === id)), []);
console.log(sorted);
// Method 2 - Map + flat
sorted = sortedArray
.map(a => unSortedArray.filter(b => b.id === a.id))
.flat();
;
console.log(sorted);
// Method 3 - flatMap
sorted = sortedArray
.flatMap(a => unSortedArray.filter(b => b.id === a.id))
;
console.log(sorted);

How to split array into three arrays by index? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have an array of 9 elements(maybe more).
I need to split by indexes into three arrays.
const array = [{id: 0}, {id: 1}, ..., {id: 8}];
I want to recieve 3 array like that:
const array0 = [{id: 0}, {id: 3}, {id: 6}];
const array1 = [{id: 1}, {id: 4}, {id: 7}];
const array2 = [{id: 2}, {id: 5}, {id: 8}];
You could take the remainfer of the index with three and address the dame group for every third element.
If necessary take destructuring assignment, like
[array0, array1, array2] = result;
const
array = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }, { id: 7 }, { id: 8 }],
result = array.reduce((r, o, i) => ((r[i % 3] = r[i % 3] || []).push(o), r), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can filter() the array using remainder operator %. For array1 check if the id % 3 === 0 and id % 3 === 1, id % 3 === 2 for next ones respectively
const array = Array(9).fill().map((x, i) => ({id: i}));
const array1 = array.filter(x => x.id % 3 === 0);
const array2 = array.filter(x => x.id % 3 === 1);
const array3 = array.filter(x => x.id % 3 === 2);
console.log('array1', array1)
console.log('array2', array2)
console.log('array3', array3)

Lodash. How to get aggregate array from array objects

For example, I have an array:
const reference = [{id: 1, value: 10}, {id: 2, value: 10}, {id: 3, value: 10}, {id: 4, value: 5}];
How to get an array values from reference like
const result = [0, 10, 20, 25];
First step always = 0
Second step 0 + 10 = 10
Third step 0 + 10 + 10 = 20
Forth step 0 + 10 + 10 + 5 = 25
You can reduce the array, and add the current value to the last sum:
const reference = [{id: 1, value: 10}, {id: 2, value: 10}, {id: 3, value: 10}, {id: 4, value: 5}];
const result = reference
.reduce((r, o, i) => {
r.push(i === 0 ? 0 : r[r.length - 1] + o.value);
return r;
}, [])
console.log(result);
You could map the values by taking a closure over the sum and take zero for the first element.
const
reference = [{ id: 1, value: 10 }, { id: 2, value: 10 }, { id: 3, value: 10 }, { id: 4, value: 5 }],
result = reference.map((sum => ({ value }, i) => sum += i && value)(0));
console.log(result);
The way I would do this would be by using the Array.reduce method as follows :
let result = [0]
reference.reduce((acc, cur) => {
result.push(Object.values(cur)[1]+result[result.length-1])
})
Hope it helps

Categories