var arr = [a, b, c];
In above array,
index 0 contains "a",
index 1 contains "b",
index 2 contains "c".
console.log(arr[0]) // will print > "a"
console.log(arr[1]) // will print > "b"
console.log(arr[2]) // will print > "b"
Is there a way so that if I want to console.log(arr[3]) then it should print "a" again, console.log(arr[4]) would be "b" and so on. If we want an index of let's say 42 like this console.log(arr[42]) then it should print any of those three string values by following the same pattern.
simply use with % like this arr[value % arr.length].
var arr = ['a', 'b', 'c'];
function finding(val){
return arr[val % arr.length];
}
console.log(finding(0))
console.log(finding(1))
console.log(finding(2))
console.log(finding(3))
console.log(finding(4))
console.log(finding(5))
console.log(finding(6))
console.log(finding(42))
We can define our custom function which give the appropriate index
function getIndex(num){
return num%3;/* modulo operator*/
}
var arr=["a","b","c"];
console.log(arr[getIndex(0)]);
console.log(arr[getIndex(1)]);
console.log(arr[getIndex(2)]);
console.log(arr[getIndex(3)]);
console.log(arr[getIndex(4)]);
console.log(arr[getIndex(5)]);
console.log(arr[getIndex(41)]);
We cannot have exactly what you are looking for. But what we can have what you are looking for by this
var arr = ["a","b","c"];
var printToThisIteration = function(n){
var length = arr.length;
for(i=0;i<n;++i)
{
console.log(arr[i%length])
}
}
Using % you can have it repeat as many times as you like.
var arr = ['a','b','c'];
let repetitions = 5;
for(var i = 0; i < repetitions; i++){
console.log(arr[i%3]);
}
Related
My goal is to create an array like this:
[{"str":"a","number":1},{"str":"a","number":2},{"str":"b","number":1},{"str":"b","number":2}]
so I wrote this javascript
abc = ["a","b"]
num = [1,2]
arr = []
a = {}
for (var i in abc)
{
str = abc[i]
a.str = str;
for(var x in num)
{
number = num[x]
a.number = number
console.log(a)
arr.push(a)
}
}
the console log looks fine, but the array looks like this:
[{"str":"b","number":2},{"str":"b","number":2},{"str":"b","number":2},{"str":"b","number":2}]
Can anyone could explain this?
This is happening because you are actually working with a reference to the same object, thus modifying the same over and over.
To fix it you must declare a new object in every iteration you want to use a different one.
Try something like this:
var abc = ["a", "b"];
var num = [1, 2];
var arr = [];
for (var i in abc) {
for (var x in num) {
var a = {};
a.str = abc[i];
a.number = num[x];
arr.push(a);
}
}
console.log(arr);
Also, don't forget to declare your variables with var or let and end your statements with ;.
As said in the comments, you’ve pushed your a object to arr many times, instead of adding four separate objects. To fix this issue, you could declare a in the for (var x in num) loop, every time as a new object (using const or let). But I’ve simplified it further, see the code below.
To iterate through JavaScript arrays, you should use .forEach method.
let abc = ['a', 'b'];
let num = [1, 2];
let arr = [];
abc.forEach(letter => {
num.forEach(number => {
arr.push({number: number, str: letter});
});
});
abc = ["a","b"]
num = [1,2]
arr = []
for (var i in abc)
{
for(var x in num)
{
a = {} ---------------- Reset "a"
str = abc[i] --------------------- 1
a.str = str; --------------------- 2
number = num[x]
a.number = number
console.log(a)
arr.push(a)
}
}
console.log(arr)
// Move 1 and 2 inside the second loop
Using map :
let tempArray = abc.map((e,i) => { return num.map((ee,ii) => { return {"str": e, "number": ee }; } ) });
$.merge(tempArray[0], tempArray[1]);
I'm currently working on a password strength calculator and then I need to know if a character appears more than once.
I know I must use regex like this occurance = password.match(/a/g).length to get ho many times a occurs, but I want to do that with each character (letter, number, symbol).
Is there a way to do that using JS / JQuery, maybe regex, other than working with an array which contains all characters I want to test ?
Something like this?
var hello = "Hello world";
var histogram = {};
for (var i = 0, len = hello.length; i < len; i++) {
var letter = hello[i];
histogram[letter] = (histogram[letter] || 0) + 1;
}
console.log(histogram);
Result:
{ H: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }
Or you may use array. Just change {} to [].
From #Noel Jose 's answer here, you can simply run this function after converting the string to an array string.split('').
function foo(arr) {
var a = [], b = [], prev;
arr.sort();
for( var i = 0; i < arr.length; i++ ){
if ( arr[i] !== prev ) {
a.push(arr[i]);
b.push(1);
} else {
b[b.length-1]++;
}
prev = arr[i];
}
return [a, b];
}
var stringToCheck = 'password';
var result = foo(stringToCheck.split(''));
// result[0] contain unique array elements and result[1] contain number of occurrences of those elements
for(var i = 0; i < result[0].length; i++){
console.log(result[0][i] + " : " + result[1][i]);
}
Passing in 'testing' will result in the following output:
e : 1
g : 1
i : 1
n : 1
s : 1
t : 2
function rall(r, s) {
var a=[],t,g=r.global;
do {t=r.exec(s);if (!t) break;
a.push(t);} while (g);
return a;
}
var r=/.*?(.)(?=(.*?\1.*))/g;
var res=rall(r,password);
res will be an array of arrays containing all matches of repeating characters.
The RegExp uses a look ahead to find out whether a found character (captured in the first group) will re-appear later in the string.
A password like secret elements would come up as:
"[["s","s","ecret elements"],
["e","e","cret elements"],
["cre","e","t elements"],
["t","t"," elements"],
[" e","e","lements"],
["le","e","ments"]]"
The second element in each sub-array is the multiply matched character.
If there are no repetitions the array will have length=0 which is easy to test like:
if (rall(r,password).length==0)
console.log('password is OK!');
If you want to use an "array-based" solution, you can try something like this:
var password= "abcdsa";
var freq = [];
for(var i = 0 ; i < password.length ; i++){
freq[password[i]] = (freq[password[i]] || 0)+1;
}
You iterate through the password once, and keep track of the ocurrances of each character that you find.
In this case the array "freq" would have something like this:
freq["a"] = 2;
freq["b"] = 1;
freq["c"] = 1;
freq["d"] = 1:
freq["s"] = 1;
Simply reduce your string into a count object. Seed the reduction with an empty object, each time a letter is encountered then that letter receives a +1 in the object where the index is the letter.
Made into a reusable function
function charCount(str){
return [].reduce.call(str,function(p,c){
p[c] = p[c] ? p[c]+1 : 1;
return p;
},{});
}
charCount("hello");//Object {h: 1, e: 1, l: 2, o: 1}
I want to find matching column elements between two 2d arrays
Means I only want to find matching string values in those given arrays
my arrays are :
//chars : "stack"
var x = [["s",0],["t",2],["a",3],["c",1],["k",2]];
// chars: "exchange"
var x = [["e",0],["x",2],["c",3],["h",1],["a",2],["n",3],["g",2],["e",3]];
Here the character "a" is matching in columns, want to store its index/value in a variable
Help, how can I do it in JavaScript (not in jQuery)
By naive brute-force loops, you should be able to find matches between two blocks like this:
var x = [["s",0],["t",2],["a",3],["c",1],["k",2]];
var y = [["e",0],["x",2],["c",3],["h",1],["a",2],["n",3],["g",2],["e",3]];
function intersection(ax,bx){
var matches = [];
ax.forEach(function (a,i){
bx.forEach(function (b,j){
if (a[0]===b[0]){ // NOTE: make sure you use STRICT EQUAL
matches.push([a[0],[i,j],[a[1],b[1]]]);
}
});
});
}
When calling intersection(x,y) it should give you an array of the intersection which looks like this:
[['a',[2,4],[3,2]]]
The 2nd element is the indices of matching elements [2,4]
where the 3rd element is the values [3,2]
If multiple matches are found, you'll get all of matches like follows:
[['a',[2,4],[3,2]], [['b',[3,5],[3,2]]]] // Just example
Try this
function getIndices(a, b) {
function toObject(columns) {
var o = {};
columns.forEach(function(column, i) {
var indices = o[column[0]] || [];
indices.push(i);
o[column[0]] = indices;
});
return o;
}
var oa = toObject(a),
ob = toObject(b),
result = [];
Object.keys(oa).forEach(function(key) {
if(ob[key]) result.push([key, oa[key], ob[key]]);
});
return result;
}
console.log(getIndices([["a", 1], ["b", 2], ["a", 5], ["c", 8]], [["c", 1], ["a", 2], ["d", 7], ["d", 9]]));
//chars : "stack"
var x = [["s",0],["t",2],["a",3],["c",1],["k",2]];
(function(){
// chars: "exchange"
var x = [["e",0],["x",2],["c",3],["h",1],["a",2],["n",3],["g",2],["e",3], ["a",7]];
var result = {};
for(var i = 0; i < x.length; ++i){
var x_key = x[i][0];
for(var j = 0; j < window.x.length; ++j){
if (x_key == window.x[j][0]){
result[x_key] = result[x_key] || [];
result[x_key].push({index: i, value: x[i][1]});
}
}
}
alert(JSON.stringify(result))
})();;
I have a string that looks like this:
str = {1|2|3|4|5}{a|b|c|d|e}
I want to split it into multiple arrays. One containing all the first elements in each {}, one containing the second element, etc. Like this:
arr_0 = [1,a]
arr_1 = [2,b]
arr_2 = [3,c]
.....
The best I can come up with is:
var str_array = str.split(/}{/);
for(var i = 0; i < str_array.length; i++){
var str_row = str_array[i];
var str_row_array = str_row.split('|');
arr_0.push(str_row_array[0]);
arr_1.push(str_row_array[1]);
arr_2.push(str_row_array[2]);
arr_3.push(str_row_array[3]);
arr_4.push(str_row_array[4]);
}
Is there a better way to accomplish this?
Try the following:
var zip = function(xs, ys) {
var out = []
for (var i = 0; i < xs.length; i++) {
out[i] = [xs[i], ys[i]]
}
return out
}
var res = str
.split(/\{|\}/) // ['', '1|2|3|4|5', '', 'a|b|c|d|e', '']
.filter(Boolean) // ['1|2|3|4|5', 'a|b|c|d|e']
.map(function(x){return x.split('|')}) // [['1','2','3','4','5'], ['a','b','c','d','e']]
.reduce(zip)
/*^
[['1','a'],
['2','b'],
['3','c'],
['4','d'],
['5','e']]
*/
Solution
var str = '{1|2|3|4|5}{a|b|c|d|e}'.match(/[^{}]+/g).map(function(a) {
return a.match(/[^|]+/g);
}),
i,
result = {};
for (i = 0; i < str[0].length; i += 1) {
result["arr_" + i] = [+str[0][i], str[1][i]];
}
How it works
The first part, takes the string, and splits it into the two halves. The map will return an array after splitting them after the |. So str is left equal to:
[
[1,2,3,4,5],
['a', 'b', 'c', 'd', 'e']
]
The for loop will iterate over the [1,2,3,4,5] array and make the array with the appropriate values. The array's are stored in a object. The object we are using is called result. If you don't wish for it to be kept in result, read Other
Other
Because you can't make variable names from another variable, feel free to change result to window or maybe even this (I don't know if that'll work) You can also make this an array
Alternate
var str = '{1|2|3|4|5}{a|b|c|d|e}'.match(/[^{}]+/g).map(function(a) { return a.match(/[^|]+/g); }),
result = [];
for (var i = 0; i < str[0].length; i += 1) {
result[i] = [+str[0][i], str[1][i]];
}
This is very similar except will generate an Array containing arrays like the other answers,
// Why doesn't this:
_.invoke(['D','C'], 'lastIndexOf', ['A','B','C'])
// Return this:
[-1,2]?
I've got a string. (Input)
'ABC'
Split into an array. (InputBuffer)
['A','B','C']
I've also got an array with arbitrary characters. (TriggerChars)
['D','E']
I want to check the last item in the InputBuffer to see if matched any of the TriggerChars.
I want to get the last occurrence of both TriggerChars in the InputBuffer.
_.invoke(['D','E'], 'lastIndexOf', ['A','B','C']);
// Returns [-1,-1] since C isn't D or E.
_.invoke(['D','C'], 'lastIndexOf', ['A','B','C']);
// Why doesn't this return [-1,2]
_.lastIndexOf(['A','B','C'],'D') == -1
_.lastIndexOf(['A','B','C'],'C') == 2
What am I not getting with Invoke?
http://underscorejs.org/#invoke
var InputBuffer = ["A","B","C"];
var TriggerChars = ["D","E"];
_.indexOf( TriggerChars, InputBuffer[InputBuffer.length-1] ) > -1;
Evaluates to true if this: I want to check the last item in the InputBuffer to see if matched any of the TriggerChars.
What you need is:
_.map(['D', 'C'], function (x) { return _.lastIndexOf(['A', 'B', 'C'], x)})
var inputBuffer = ["A","B","C"];
var triggerChars = ["D","E"];
triggerChars.indexOf(inputBuffer[inputBuffer.length-1]) > -1
or just skip underscore, the exact same solution above except the dependency,
ok I updated it alittle
var inputBuffer = ["A","B","C"];
var triggerChars = ["D","C"];
var index = [];
for(var i = 0; i < triggerChars.length; i++){
index.push(inputBuffer.lastIndexOf(triggerChars[i]));
}
console.log(index);
-> [-1,2]