Combining array of strings in Javascript two at a time - javascript

I have an array of strings, how I can make combination of elements two at a time separated by underscore.
var array = ['a', 'b', 'c']; the output should be ['a_b', 'a_c', 'b_c']
How I can do this in Javascript?
Please note that this is different from Permutations in JavaScript? since we need a combination of two and cannot be array elements cannot be replicated.
Thanks.

You can use nested loops to achieve something like that:
var arr = ['a', 'b', 'c'];
var newArr = [];
for (var i=0; i < arr.length-1; i++) { //Loop through each item in the array
for (var j=i+1; j < arr.length; j++) { //Loop through each item after it
newArr.push(arr[i] + '_' + arr[j]); //Append them
}
}
console.log(newArr);
I've elected to mark this as a community post because I think a question that shows no attempt shouldn't merit reputation, personally.

A solution could be:
function combine(arr) {
if (arr.length === 1) {
return arr; // end of chain, just return the array
}
var result = [];
for (var i = 0; i < arr.length; i++) {
var element = arr[i] + "_";
for (var j = i+1; j < arr.length; j++) {
result.push(element + arr[j]);
}
}
return result;
}

It should be an double for, something like this:
var output = [];
var array = ['a', 'b', 'c'];
for(var i = 0; i < array.length; i++){
for(var j = 0; j < array.length; j++) {
output.push(array[i] + "_" + array[j]);
}
}
The output is:
["a_a", "a_b", "a_c", "b_a", "b_b", "b_c", "c_a", "c_b", "c_c"]

Related

How can I delete special characters inside a nested array?

So let's say I have an array like this, what would be the most effiecient way to go through the array and erase all the '$' signs?
I have tried many different approaches but none of them seem to work properly, any thoughts?
const myArray = [
['$','H','e','$','$','l'],
['l','$','o','$','W','o'],
['r','l','$','d','$','M'],
['y','$','N','a','$','m'],
['e','$','i','s','$','p'],
['a','b','$','l','$','$'],
['$','o','$','$','w','$']
];
const myArray = [
['$','H','e','$','$','l'],
['l','$','o','$','W','o'],
['r','l','$','d','$','M'],
['y','$','N','a','$','m'],
['e','$','i','s','$','p'],
['a','b','$','l','$','$'],
['$','o','$','$','w','$']
];
const result = myArray.map(arr => arr.filter(letter => letter != '$'));
console.log(result);
A nested for loop will work very quickly:
for (var i = 0; i < myArray.length; i++){
for (var j = 0; j < myArray[i].length; j++){
if (myArray[i][j]=='$')
myArray[i][j]==''
}
}
You can just filter the individual Arrays in myArray like so:
for (let i = 0; i < myArray.length; i++) {
myArray[i] = myArray[i].filter(x => x != '$');
}

Sort an array of strings based on a character in the string

I am trying to sort an array of strings based on a character inside each of those strings. So far, I have this
function doMath(s) {
let arr = s.split(' ');
let letterArr = [];
let sortedArr = [];
let n = 0;
for (var i = 0; i < arr.length; i++) {
n = arr[i].indexOf(arr[i].match(/[a-z]/i));
letterArr.push(arr[i][n]);
}
letterArr.sort();
console.log(letterArr);
for (i = 0; i < arr.length; i++) {
for (var j = 0; j <= arr[i].length; j++) {
if (arr[i].indexOf(letterArr[j]) > -1) {
sortedArr.unshift(arr[i]);
}
}
}
console.log(sortedArr);
}
doMath("24z6 1x23 y369 89a 900b");
The problem is shown when I log this array. If I use sortedArr.push(arr[i]);,
then the output is:
["24z6", "1x23", "y369", "89a", "900b"]
However, when I use sortedArr.unshift(arr[i]);, I get the output:
["900b", "89a", "y369", "1x23", "24z6"]
I am not sure why the b comes before the a.
I just want it to be a-z for the sorting. I tried push() and it is correct but backwards (z-a). When I try unshift(), it's correct except the b and a are switched.
function doMath(s) {
return s.split(' ').sort(function (a,b) {
return a.match(/[a-z]/i)[0].localeCompare(b.match(/[a-z]/i)[0])})
}
console.log(doMath("24z6 1x23 y369 89a 900b"));

Cannot read property 'push' of undefined multidimensional array

I'm trying to solve this problem: Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array. For example:
chunk(['a', 'b', 'c', 'd'], 2)
should return
[['a'. 'b'], ['c', 'd']]
My code is as follows:
function chunk(arr, size) {
var newArr = [[]];
for(i = 0; i < arr.length; i++) {
for(j = 0; j < size; j++) {
newArr[i].push(arr[i + j]);
}
}
return newArr;
}
It gives an error: Cannot read property 'push' of undefined. Why is this happening and how can I fix this?
You could do this with nested loops, but why not go for a simpler approach and use array.slice()?
function chunk( input, size ) {
var output = [];
for( i = 0; i < input.length; i += size ) {
output.push( input.slice( i, i + size ) );
}
return output;
}
After
for(i = 0; i < arr.length; i++) {
you must initialize the one-dimensional array:
newArr[i] = [];
This will solve the error, but not produce the result you want. I think you need something like this:
for (i = 0; i < ceil(arr.length / size); i++) {
newArr[i] = [];
for (j = 0; j < size; j++) {
if (i * size + j >= arr.length)
break;
newArr[i].push(arr[i * size + j]);
}
}

How to add array of arrays in javascript

I have a Javascript array with multiple arrays inside. I was trying to loop through the array to return an aggregated array. So far I have done following with no luck:
var a = [[1,2,3],[4,5,56],[2,5,7]];
var x = [];
for ( var i = 0; i < a.length; i++) {
for ( var j = 0; j < a[i].length; j++) {
console.log(a[i][i] = a[i][j]+a[j][i]);
}
}
I am trying to obtain the following result:
console.log(a); // -> [7,12,66]
Any suggestions or pin points where I can look for examples of similar things would be appreciated.
assuming the elements of a has the same length, the following should work
var x=[];
for(var i=0; i<a[0].length; i++){
var s = 0;
for(var j=0; j<a.length; j++){
s += a[j][i];
}
x.push(s);
}
a[0].map(function(b,i){return a.reduce(function(c,d){return c+d[i];},0);})
// [7, 12, 66]
From dc2 to dc1, try this:
var a = [[1,2,3],[4,5,56],[2,5,7]];
var x = [];
for ( var i =0; i < a.length; i++){
for ( var j = 0; j < a[i].length; j++){
x[j] = x[j] || 0;
x[j] = x[j] + a[i][j];
}
}
This worked in testing, and doesn't error with different array lengths.

How to access array in circular manner in JavaScript

I have an array like [A,B,C,D]. I want to access that array within a for loop like as
var arr = [A,B,C,D];
var len = arr.length;
for(var i = 0; i<len; i++){
0 - A,B,C
1 - B,C,D
2 - C,D,A
3 - D,A,B
}
I want to access that like in JavaScript, any ideas?
Answering to the main question, someone can access an array in a circular manner using modular arithmetic. That can be achieved in JavaScript with the modulus operator (%) and a workaround.
Given an array arr of a length n and a value val stored in it that will be obtained through an access index i, the circular manner, and safer way, to access the array, disregarding the value and sign of i, would be:
let val = arr[(i % n + n) % n];
This little trick is necessary -- someone can not use the modulus result straightforwardly -- because JavaScript always evaluates a modulus operation as the remainder of the division between dividend (the first operand) and divisor (the second operand) disconsidering their signs but assigning to the remainder the sign of the dividend. That behavior does not always result in the desired "wrap around" effect of the modular arithmetic and could result in a wrong access of a negative position of the array.
References for more information:
https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/what-is-modular-arithmetic
https://en.wikipedia.org/wiki/Modular_arithmetic
https://en.wikipedia.org/wiki/Modulo_operation
https://dev.to/maurobringolf/a-neat-trick-to-compute-modulo-of-negative-numbers-111e
Try this:
var arr = ["A","B","C","D"];
for (var i=0, len=arr.length; i<len; i++) {
alert(arr.slice(0, 3).join(","));
arr.push(arr.shift());
}
Without mutating the array, it would be
for (var i=0, len=arr.length; i<len; i++) {
var str = arr[i];
for (var j=1; j<3; j++)
str += ","+arr[(i+j)%len]; // you could push to an array as well
alert(str);
}
// or
for (var i=0, len=arr.length; i<len; i++)
alert(arr.slice(i, i+3).concat(arr.slice(0, Math.max(i+3-len, 0)).join(","));
Simply using modulus operator you can access array in circular manner.
var arr = ['A', 'B', 'C', 'D'];
for (var i = 0, len = arr.length; i < len; i++) {
for (var j = 0; j < 3; j++) {
console.log(arr[(i + j) % len])
}
console.log('****')
}
how about this one-liner I made ?
var nextItem = (list.indexOf(currentItem) < list.length - 1)
? list[list.indexOf(currentItem) + 1] : list[0];
for (var i = 0; i < arr.length; i++) {
var subarr = [];
for (var j = 0; j < 3; j++) {
subarr.push(arr[(i+j) % arr.length]);
}
console.log(i + " - " + subarr.join(','));
}
One line solution for "in place" circular shift:
const arr = ["A","B","C","D"];
arr.forEach((x,i,t) => {console.log(i,t); t.push(t.shift());});
console.log("end of cycle", arr); // control: cycled back to the original
logs:
0 Array ["A", "B", "C", "D"]
1 Array ["B", "C", "D", "A"]
2 Array ["C", "D", "A", "B"]
3 Array ["D", "A", "B", "C"]
"end of cycle" Array ["A", "B", "C", "D"]
If you want only the first 3 items, use:
arr.forEach((x,i,t) => {console.log(i,t.slice(0, 3)); t.push(t.shift());});
Another solutions:
var arr = ['A','B','C','D'];
var nextVal = function (arr) {
return arr[( ( ( nextVal.counter < ( arr.length - 1 ) ) ? ++nextVal.counter : nextVal.counter=0 ) )];
};
for(var i=0;i<arr.length;i++){
console.log(nextVal(arr)+','+nextVal(arr)+','+nextVal(arr));
}
And based on Modulo :
var arr = ['A','B','C','D'];
var len = arr.length;
var nextVal = function (arr, dir = 1) {
if ( dir < 0 ) { nextVal.counter--;}
let i = (nextVal.counter % len + len) % len;
if ( dir > 0 ) { nextVal.counter++; }
return arr[i];
};
nextVal.counter=0;
for(var i=0;i<arr.length;i++){
console.log(nextVal(arr)+','+nextVal(arr)+','+nextVal(arr));
}
// in reverse
console.log('-------------------');
nextVal.counter=0;
for(var i=0; i<10; i++) {
console.log(nextVal(arr, -1)+','+nextVal(arr, -1)+','+nextVal(arr, -1));
}
You could get the sliced part from index and the rest of slicing from start, if necessary.
This appraoch does not mutate the array.
const
getCircular = (array, size) => array.map((_, i, a) => [
...a.slice(i, i + size),
...a.slice(0, i + size < a.length ? 0 : i + size - array.length)
]);
console.log(getCircular(['A', 'B', 'C', 'D'], 3).map(a => a.join('')));
console.log(getCircular(['A', 'B', 'C', 'D'], 5).map(a => a.join('')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
We can simply achieve this by using Array.splice() method along with the Destructuring assignment
Live Demo :
// Input array.
let arr = ['A', 'B', 'C', 'D'];
// Finding the length of an array.
const len = arr.length;
// Iterattion based on array length.
for(let i = 0; i < len; i++) {
const splittedArr = arr.splice(0, 3);
arr.push(splittedArr[0]);
arr = [splittedArr[1], splittedArr[2], ...arr]
console.log(splittedArr);
}

Categories

Resources