Multi-push vs. multi-map [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 days ago.
The community is reviewing whether to reopen this question as of 4 days ago.
Improve this question
I'm asked to get attributes collection out of an array object,
let a = [
{name:'aname',age:21},
{name:'bname',age:22},
{name:'cname',age:23},
{name:'dname',age:24},
{name:'ename',age:25},
{name:'fname',age:26},
{name:'gname',age:27}]
// wanted
let ok = {
names:'aname;bname;cname;dname;ename;fname;gname',
ages:'21;22;23;24;25;26;27'
}
and I got 2 ways of doing it:
alpha just using map of an array:
// alpha
let res = {
names:'',
ages:''
}
res.names=a.map(iter=>iter.name).join(';')
res.ages=a.map(iter=>iter.age).join(';')
//then return res
// ========================================================
and beta just iterate the array and append each attribute in the tabulation array:
// beta
let res = {
names:[],
ages:[]
}
a.forEach(iter=>{
res.names.push(iter.name)
res.ages.push(iter.age)
})
// then handle res's fields
ok.names = res.names.join(';')
ok.ages = res.ages.join(';')
so which way should I use to get the collection? Will alpha get slower or faster than beta when the objects in a get lots of fields(attrs)?

Both approaches are good. I'd say it depends on your personal preference what you'd want to use.
However, It seems to me that if you are aiming for performance, the following would yield better results.
let a = [
{name:'aname',age:21},
{name:'bname',age:22},
{name:'cname',age:23},
{name:'dname',age:24},
{name:'ename',age:25},
{name:'fname',age:26},
{name:'gname',age:27}]
let ok = { names: '', ages: ''}
for (let i = 0; i < a.length; i++){
const iter = a[i]
ok.names += iter.name + ";";
ok.ages += iter.age + ";";
}
ok.names = ok.names.slice(0,-1)
ok.ages = ok.ages.slice(0,-1)
console.log(ok)
This apporach eliminates the need to create new arrays or joining them (join is a heavy operation). Just create the string you want and at the end of it all, remove the one extra semicolon.

I consider that alfa is simpler and clearer for me, but I guess it is up to you...

Related

Difficult to find smallest e biggest number [closed]

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 4 months ago.
Improve this question
im trying to Find the Smallest and Biggest Numbers. i can do this in for > let. but when i try to put this in a function it does not work.
const myNumbers = [1111, 245, 535 ,222, 221,12,233444];
function findnum(){
for (let i=0; i < myNumbers.length ; i++ ){
const smallNum = Math.min(...myNumbers)
const bigNum = Math.max(...myNumbers)
break
}
}
result = findnum(smallNum,bigNum)
console.log(result)
If you pass two variables to a function like this result = findnum(smallNum, bigNum), then you should have the function's signature with two arguments, like this:
function findnum(smallNum, bigNum){
Pay attention that smallNum and bigNum only exist inside the function. As #pilchard mentioned, in your code you don't need arguments, the loop is unnecessary, and the function needs a return.
This should work.
const myNumbers = [1111, 245, 535 ,222, 221, 12, 233444];
function findnum(){
const smallNum = Math.min(...myNumbers)
const bigNum = Math.max(...myNumbers)
return [smallNum, bigNum]
}
result = findnum()
console.log(result)

React Redux is creating unnecessary indexes [closed]

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 1 year ago.
Improve this question
I'm trying to get data from my server and format that data into an indexed array and storing that in my store. The problem is when I try to manually define the indexes Redux automatically nulls any indexes that were undefined. Because I have one index with a very large number Redux indexes many unnecessary items and crashes.
Image of the bug:
Image of my code:
This happens because langStrings[i].LayoutTypeId is an huge number and if you do filteredLangStrings[langStrings[i].LayoutTypeId] = [] javascript creates an array of length langStrings[i].LayoutTypeId with all the elements set to null.
To avoid this, you should change your filteredLangStrings shape in this way:
let filteredLangStringsIndex = 0;
for(let i = 0; i < langStrings.length; i++) {
if(langStrings[i].LanguageId === langId) {
let index = langStrings[i].LayoutTypeId;
if (langStrings[i].Msg !== "") {
filteredLangStrings[filteredLangStringsIndex] = {};
filteredLangStrings[filteredLangStringsIndex].index = index;
filteredLangStrings[filteredLangStringsIndex].Msg = langStrings[i].Msg; ​
​ filteredLangStringsIndex ++;
​}
​ }
}
This creates something like:
filteredLangStringsIndex = {"0": {index: 89746, Msg: "message"},
"1": {index: 54543, Msg: "another message"}, ...}
In this way you have a smaller filteredLangStringsIndex by keeping index and Msg informations.

How to search in localstorage for specific word and get entire key and value? [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
On click i created localstorage item "storageKey__list" and value is "example.com"
I need to get all item keys and values ends with "__list" and then get entire key and value.
Result must be:
"storageKey__list , example.com"
You could grab the entries in localStorage using Object.entries() and then use .filter() to obtain only the entires ending in "__list" by using .endsWith():
Object.entries(localStorage).filter(([key]) => key.endsWith('__list'));
Output:
[["storageKey__list", "example.com"]]
A more browser friendly version of the code above could be to use the following:
Object.keys(localStorage).filter(function(key) {
return /__list$/.test(key);
}).map(function(key) {
return [key, localStorage.getItem(key)];
});
Output:
[["storageKey__list", "example.com"]]
Try this:
/** #type {[string, string][]} */
const keyValuePairs = [];
for (let i = 0, l = localStorage.length; i < l; i++) {
const key = localStorage.key(i);
if (key.endsWith("__list"))
keyValuePairs.push([ key, localStorage.getItem(key) ]);
}
console.log(keyValuePairs);

I want to create a little test-program with "dices" with javascript [closed]

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 4 years ago.
Improve this question
I am trying to figure out how I can create a "game" where I have three dices, and three bets. If any of the bets hits, I will be granted 1 point, else nothing happens.
Example variables and arrays I would like to use;
var points = 1;
var slot1 = Math.floor((Math.random()*6)+1);
var slot2 = Math.floor((Math.random()*6)+1);
var slot3 = Math.floor((Math.random()*6)+1);
var dices = [slot1, slot2, slot3];
function Bet(bet1, bet2, bet3) {
"NEED HELP WITH THE CODE HERE"
}
Bet(1,2,3);
Thanks alot for all kinds of help!
I think a nudge in the right direction is more appropriate than a ready-to-go answer, since your question smells a little bit like homework :-)
You basically need to cross-check each item from both lists. You can do this with either a nested for .. in loop or a call to .some() with a nested .contains(). The latter will give you the cleanest solution. Docs
Alternatively, you can use Tagas' solution but that would make your function less reusable. If the number of bets vary, you'll need to adjust your function..
Try this:
function rollDice() {
//generate a number between 1 to 6
return Math.floor(Math.random() * (6 - 1 + 1)) + 1;
}
function makeBet(bet1, bet2, bet3) {
let slot1 = rollDice(),
slot2 = rollDice(),
slot3 = rollDice();
console.log('Slot 1:', slot1);
console.log('Slot 2:', slot2);
console.log('Slot 3:', slot3);
if(bet1 == slot1 || bet2 == slot2 || bet3 == slot3) {
//return 1 point as there is a match
return 1;
}
//return nothing as there was no match
return 0;
}
//Make a bet!
makeBet(1, 2, 3);

Convert string into array of int [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I want to convert "1,2,3" to [1,2,3].
But there is an exception when converting "" to array. Because I get [""]. That is not valid for my case. So I need to check is it number or String. Let see this in code
function someWayToParse(some_string) {
var final_product = [];
var tmp_array = some_string.split(',');
//if some_string == "" tmp_array will result [""];
if (tmp_array[0].length===0)
return [];
for (var item in tmp_array)
final_product.push(parseInt(tmp_array[item], 10));
return final_product;
}
var stringToParse = "1,2,3";
var array_of_ints = someWayToParse(stringToParse);
I am just looking the best way to do this in a function and avoid possible mistakes.
Please be memory efficient, for my curiosity's sake.
Smaller code for it would be:
function myConverter(string) {
if (!string) return [];
return string.split(',').map(Number);
}
console.log(myConverter('1,2,3'));

Categories