I want to execute int function based on specific times (in seconds) from the times array.
let times = [
//[type, startTime, endTime]
['A', '2', '5'],
['B', '7', '9'],
['C', '12', '15'],
];
function int(startTime, endTime){
console.log(startTime);
console.log(endTime);
};
So we should execute the int function in seconds 2 , 7 and 12 (the second element in the inner arrays)
Note: we should be able to pass arrays to times array and the code should still work.
I have no idea if this is possible and need a hand to find a solution.
I would do it like this. The code should explain itself but if you have any questions let me know.
let times = [
//[type, startTime, endTime]
['A', '2', '5'],
['B', '7', '9'],
['C', '12', '15'],
];
function int(startTime, endTime) {
console.log(startTime);
console.log(endTime);
};
times.forEach((elem)=> {
setTimeout(() => {
int(elem[1], elem[2]); // Call to function
}, elem[1] * 1000); // Conversion to seconds
});
Related
I want to parse this dictionary:
var data = {'Charlie':
{'keys':
{'a': '1',
'b':['1', '2', '3'],
'c': '3'},
},
'Derek':
{'keys':
{'a': '10',
'b': ['9', '8', '7'],
'c': '9'},
}
};
But I want "Charlie" and "Derek" to appear as li names instead of Dummy. Still - I can't since I don't see them in response. They disappear after parsing, leaving:
'keys':
{'a': '1',
'b':['1', '2', '3'],
'c': '3'}
and
'keys':
{'a': '10',
'b': ['9', '8', '7'],
'c': '9'},
The full code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div>
<h3>Div underneath</h3>
<ul id="main-ul">
</ul>
</div>
</body>
<script>
var data = {'Charlie':
{'keys':
{'a': '1',
'b':['1', '2', '3'],
'c': '3'},
},
'Derek':
{'keys':
{'a': '10',
'b': ['9', '8', '7'],
'c': '9'},
}
};
lay_out_tab_structure(data)
function lay_out_tab_structure(response) {
console.log("response in lay_out_tab is", response)
var ul = $('#main-ul');
for (const [key, value] of Object.entries(response)) {
var li = document.createElement('li')
var div = document.createElement('div')
li.append(div);
ul.append(li);
console.log("The key-value pair before passing is", (key, value))
create_row(li, (key, value))
}
};
function create_row(listItem, content) {
console.log("Content in create row is", content)
var mainDiv = $(listItem).children('div');
var name = $('<p class="css-big-letter machine-name">'+'<a style="color:inherit;">'+"Dummy"+'</a>'+'</p>');
var titleDiv = $('<div style="position:relative;margin-bottom:1%;"></div>');
titleDiv.append(name);
mainDiv.append(titleDiv);
var RowDiv = $('<div></div>');
$(mainDiv).append(RowDiv);
};
</script>
</html>
Can you help me?
I have already tried this solution and I couldn't get it working:
Object.entries() turning keys into arrays
Object.entries() will, as your code reflects, provide you with a list of 2-element arrays. Your code destructures each of those arrays into your key and value variables. All of that is fine.
However, when you want to pass both the key and the value to another function, you'll have to either pass each as a separate parameter, or else collect them back into a 2-element array. The statement
create_row(li, (key, value))
does not do either of those things. The expression (key, value) is a comma expression and will evaluate only to value, as you've found out. Thus, you could either change create_row() to accept a total of 3 parameters and pass key and value individually, or else group those two into a new array:
create_row(li, [key, value])
Either way will work. If you go with the array, then inside create_row() the key will be content[0] and the value will be content[1].
I am trying to make tic tac toe game in vanilla javascript. If I use ! to flip the value of object boolean property , it is changed to what it is defined in global memory object (as soon as it is out of its execution context), however If I flip by using = equal sign, it stays same. aren't they both doing same thing(flipping value)?? Any explanation would be appreciated.
Here's my code.
// we need an object for storing the state of our game.
const game = {
xTurn: true,
xState: [],
oState: [],
winningStates: [
// Rows
['0', '1', '2'],
['3', '4', '5'],
['6', '7', '8'],
// Columns
['0', '3', '6'],
['1', '4', '7'],
['2', '5', '8'],
// Diagonal
['0', '4', '8'],
['2', '4', '6']
]
}
document.addEventListener('click',e=>{
const target = e.target;
console.log('initializing code')
const isCell = target.classList.contains('grid-cell')
const isDisabled = target.classList.contains('disabled');
if(isCell && !isDisabled){
const cellValue = target.dataset.value;
if(game.xTurn){
game.xState.push(cellValue)
}else{
game.oState.push(cellValue)
}
target.classList.add('disabled')
target.classList.add(game.xTurn ? 'x' : 'o')
// if(game.xTurn){
// target.classList.add('x')
// }else{
// target.classList.add('o')
// }
console.log(game.xTurn)
game.xTurn = !game.xTurn;
// game.xTurn = false;
console.log(game.xTurn)
}
})
I have a text and want to summarize it , i want change this array :
Array 1
[
'CALX', '11.10', '21',
'01', '08', 'EGLD',
'USDT', 'LDFDFC', 'ZONE',
'238.5', '233', 'LEVERAGE',
'3', 'X', 'TARGET',
'1', '243.9', 'TARGET',
'2', '248', 'TARGET',
'3', '254', 'TARGET',
'4', '260', 'H',
'GD', 'S', 'AFCA'
]
to this :
Array 2
[
'CALX', '11.10', '21',
'01', '08', 'EGLDUSDTLDFDFCZONE',
'238.5', '233', 'LEVERAGE',
'3', 'XTARGET',
'1', '243.9', 'TARGET',
'2', '248', 'TARGET',
'3', '254', 'TARGET',
'4', '260', 'HGDSAFCA',
]
as you can see , I want all the letters to stick together until they reach a number,and each number should be in an element of the array
This is the code that can be used to convert text to an Array1
const input = 'CALX, [11.10.21 01:08] $EGLD/USDT #Ldfdfc zone : 238.5 - 233 "LEVERAGE" : 3x TARGET1 : 243.9 TARGET 2 : 248 TARGET 3 : 254 TARGET 4 : 260 h.gd.s afca. `~!##$%^&*()_-+=-/?><'
const text = text.toUpperCase().match(/[a-z]+|\d+(?:\.\d+)?/gi);
so how can i change the Array1 to Array2?
sorry for my English and thank you for your help.
Based on the initial string, to get the desired array as output you don't have to convert it to an array to process it again.
You can use a pattern similar like the one that you tried with an alternation | but instead of matching [a-z]+ you can capture 1 or more non digits using (\D+) in a group.
Then in the callback of replace, you can remove the unwanted characters if there is a match for the group 1. The unwanted characters are [\W_]+ or one more non word chars including the underscore.
If there is no group, you can return the match (the digits) between delimiters, where you can split on the delimiters afterwards to create the final array.
const input = 'CALX, [11.10.21 01:08] $EGLD/USDT #Ldfdfc zone : 238.5 - 233 "LEVERAGE" : 3x TARGET1 : 243.9 TARGET 2 : 248 TARGET 3 : 254 TARGET 4 : 260 h.gd.s afca. `~!##$%^&*()_-+=-/?><'
text = input
.toUpperCase()
.replace(/\d+(?:\.\d+)?|(\D+)/g,
(m, g1) => g1 ? g1.replace(/[\W_]+/g, '') : `#${m}#`
);
console.log(text.split(/#+/));
One of the solution could look like this:
let arr = [
'CALX', '11.10', '21',
'01', '08', 'EGLD',
'USDT', 'LDFDFC', 'ZONE',
'238.5', '233', 'LEVERAGE',
'3', 'X', 'TARGET',
'1', '243.9', 'TARGET',
'2', '248', 'TARGET',
'3', '254', 'TARGET',
'4', '260', 'H',
'GD', 'S', 'AFCA'
]
function handleArray(a) {
let result = [];
let stringItem = '';
a.forEach((el) => {
// If number then check if we have previous string and push
// it to the result.
// Also push number as next element
if (/\d/.test(el)) {
if (stringItem) {
result.push(stringItem);
// Clear string variable
stringItem = '';
}
result.push(el)
} else {
// Concat ongoing string, don't push to result
stringItem += el;
}
})
return result;
}
console.log(handleArray(arr))
I'll try my best to explaing as throughly as possible but first I'll just paste what I have so far:
var test = 'select imei, phone_number from userinfo';
const result = await pgClient.query(test);
const resultString = result.rows;
var a = [];
for(let i = 0; i < resultString.length; i +=1){
let obj = resultString[i];
//let data = [obj];
// res = data.reduce((acc, curr) => {
// acc[curr.imei] = curr.phone_number;
// return acc;
// }, {} );
a.push(obj)
}
console.log(a)
so basically after querying that select statment, I get an obj like this {imei, number} and then push that to an array so it more looks like this
var jsObjects = [
{imei: '11', number: '+11'},
{imei: '12', number: '+12'},
{imei: '13', number: '+13'},
{imei: '14', number: '+14'}
];
But if you uncomment the code above and replace a.push(obj) with a.push(res) it can also look like this
[
{ '11': '+11' },
{ '12': '+12'},
]
So the MAIN reason for all of this is becasue im trying to create a function so that
if (a.imei('11')) {
return a.phonenumber('+11')
}
Return the phone number associated with the given imei number.
And the actual question is which format is best to access key, value pair? and how would i access the actual value based on the key? Sorry for being all over, I really dont know how else to explain and ask this. Thank you
I think I understand that you'd like a fast lookup of a number value given an "imei" value. The loop as written in the OP doesn't do anything to the result string except move the same values into a new array called a, so either with a or resultString, do this...
const jsObjects = [
{imei: '11', number: '+11'},
{imei: '12', number: '+12'},
{imei: '13', number: '+13'},
{imei: '14', number: '+14'}
];
const imeiIndex = jsObjects.reduce((acc, obj) => {
acc[obj.imei] = obj.number;
return acc;
}, {});
console.log(imeiIndex)
With that, given an "imei" value later, the associated number can be looked up fast with...
let someImeiValue = '14';
let quicklyLookedupNumber = imeiIndex[someImeiValue]; // <- this will be '+14'
Also, note...
It's often a good idea to keep the whole object being indexed in the way just described, like this:
const jsObjects = [
{imei: '11', number: '+11', someOtherProp: 1 },
{imei: '12', number: '+12', someOtherProp: 2 },
{imei: '13', number: '+13', someOtherProp: 3 },
{imei: '14', number: '+14', someOtherProp: 4 }
];
const imeiIndex = jsObjects.reduce((acc, obj) => {
acc[obj.imei] = obj; // <-- NEW: store the whole object in the index
return acc;
}, {});
// now indexed data contains as much info as the original array
console.log(imeiIndex);
let key = '12';
console.log(`the object at key ${key} is ${JSON.stringify(imeiIndex[key])}`);
I wonder if there is a precise way for getting filtered an unfiltered elements of an array in Javascript, I mean, like, in one go.
Currently, I use a logic like follows:
const myArray = ['a', 'b', 'c', 'd', 'e']
const filterArray = ['a', 'b']
// I want to combine those two expressions somehow
const filteredInResult = myArray.filter(e => filterArray.includes(e))
const filteredOutResult = myArray.filter(e => !filterArray.includes(e))
console.log(filteredInResult)
console.log(filteredOutResult)
I felt like a destructuring-like way might already be there to achieve it, but anyway, I prefer asking you guys if there is a way for getting filtered in & out results in one shot.
EDIT: SO keeps alerting me if this question is similar to the question here, but I used string comparison and includes for brewity above but the filtering expression may be more complex than that. So, the I must underline that the focus of the question is not on difference of two string arrays. I am leaving another example and hope the questions won't be merged :D
// A more complex use case
const myArray = [
{id: 1, value: 'a'},
{id: 2, value: 'b'},
{id: 3, value: 'c'},
{id: 4, value: 'd'},
{id: 5, value: 'e'},
]
const filterArray = ['a', 'b']
// I want to combine those two expressions somehow
const filteredInResult = myArray.filter(e => filterArray.includes(e.value))
const filteredOutResult = myArray.filter(e => !filterArray.includes(e.value))
console.log(filteredInResult)
console.log(filteredOutResult)
If you're worried about iterating twice over the myArray, you might first consider reducing the computational complexity. Because each iteration of the loops calls Array.prototype.includes, and the complexity of Array.prototype.includes is O(n), your code has an overall complexity of O(n ^ 2). (outer loop: O(n) * inner loop: O(n)). So, consider fixing that first: use a Set and Set.has, an O(1) operation, instead of an array and .includes. This is assuming that your actual filterArray is large enough that computational complexity is something to worry about - sets do have a bit of an overhead cost.
As for the other (main) part of the question, one option is to create the two result arrays outside, then push to the appropriate one while iterating:
const myArray = ['a', 'b', 'c', 'd', 'e']
const filterArray = new Set(['a', 'b'])
const filteredInResult = [];
const filteredOutResult = [];
for (const e of myArray) {
(filterArray.has(e) ? filteredInResult : filteredOutResult).push(e);
}
console.log(filteredInResult)
console.log(filteredOutResult)
Could also use reduce, though I don't think it looks very good:
const myArray = ['a', 'b', 'c', 'd', 'e']
const filterArray = new Set(['a', 'b'])
const { filteredInResult, filteredOutResult } = myArray.reduce((a, e) => {
a[filterArray.has(e) ? 'filteredInResult' : 'filteredOutResult'].push(e);
return a;
}, { filteredInResult: [], filteredOutResult: [] });
console.log(filteredInResult)
console.log(filteredOutResult)
You could use .reduce() instead of .filter(), where you use the (numeric) boolean value of includes() as the index for your accumilator like so:
const myArray = ['a', 'b', 'c', 'd', 'e'];
const filterArray = ['a', 'b'];
const [fOut, fIn] = myArray.reduce((a, n) => {
a[+filterArray.includes(n)].push(n);
return a;
}, [[], []]);
console.log(fIn);
console.log(fOut);
I could not destruct but this seems to be simpler to read than the reduce offered elsewhere
const myArray = ['a', 'b', 'c', 'd', 'e']
const filterArray = ['a', 'b']
let filteredOutResult = [];
const filteredInResult = myArray.filter(item => {
if (filterArray.includes(item)) return item;
filteredOutResult.push(item);
});
console.log(filteredInResult,filteredOutResult)
A solution with ramda's partition.
const
array = ['a', 'b', 'c', 'd', 'e'],
filter = ['a', 'b'],
[filteredInResult, filteredOutResult] = R.partition(v => filter.includes(v), array);
console.log(...filteredInResult); // a b
console.log(...filteredOutResult) // c d e
<script src="http://cdn.jsdelivr.net/ramda/latest/ramda.min.js"></script>
One native answer is to use Array#reduce:
const { in, out } = myArr.reduce((acc, v) => {
(filterArray.includes(v) ? acc.in : acc.out).push(v);
return acc;
}, { in: [], out: [] });
And then destructure the returned object