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]);
}
}
Related
I want to make an array w[i][j] where each w[i][j] is itself an array of numbers.
If I try to do it naively by declaring an empty array w
and assigning variable by looping through it I get the error:
const w : Array<Array<Array<number>>> = [];
for(let i = 0; i < N; i++){
for(let j = 0; j < N; j++){
w[i][j] = [1,2,3];
}
}
TypeError: Cannot set property '0' of undefined.
Instead I am forced to initialze each element of the array to be empty, using the below code. Only after doing this am I able to make the array with no problems. This can't be the best practice. What am I misunderstanding and what should I write instead?
const w : Array<Array<Array<number>>> = [];
for(let i = 0; i < N; i++){
w[i] = [];
for(let j = 0; j < N; j++){
w[i][j] = [];
}
}
You are getting the error because w[i] is not set when you are trying to set w[i][j].
Fix
Do an init or load in the loop e.g.
const N = 5;
const w: Array<Array<Array<number>>> = [];
for (let i = 0; i < N; i++) {
w[i] = w[i] || [];
for (let j = 0; j < N; j++) {
w[i][j] = [1, 2, 3];
}
}
console.log(w); // All good 🌹
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"]
I need help merging two arrays without using any of the array built in functions ( no concat, push, pop, shift, replace, sort, splice, etc)
And I've got to this point but I'm stuck.
function addTwoArrays(arr1, arr2){
var merge = [], p;
for(p = 0; p < arr1.length; p++){
merge[arr1[p]] = true;
}
for(p = 0; p < arr2.length; p++){
merge[arr2[p]] = true;
}
return Object.keys(merge);
}
window.alert(addTwoArrays([1,2,3,4],[4,3,2,1]));
return is 1,2,3,4 - instead of 1,2,3,4,4,3,2,1
You only need to loop once - simply take arr1.length as a start index and add to the array:
function addTwoArrays(arr1, arr2) {
let start = arr1.length;
for (let i = 0; i < arr2.length; i++) {
arr1[start++] = arr2[i];
}
return arr1;
}
console.log(addTwoArrays([1, 2, 3, 4], [4, 3, 2, 1]));
Keys are unique in a JSON object. So, Object.keys() will return unique occurrences of each element.
Instead try this:
function addTwoArrays(arr1, arr2){
var merge = [], p, index = 0;
for(p = 0; p < arr1.length; p++){
merge[index++] = arr1[p];
}
for(p = 0; p < arr2.length; p++){
merge[index++] = arr2[p];
}
return merge;
}
window.alert(addTwoArrays([1,2,3,4],[4,3,2,1]));
function mergedArray(arrayOne, arrayTwo) {
let newArr = arrayOne
let x = arrayOne.length
let y = arrayTwo.length
let z = arrayOne.length + arrayTwo.length
let i, j
for (i = x, j = 0; i < z && j < y; i++, j++) {
newArr[i] = arrayTwo[j]
}
return newArr
}
I have the following function to get all of the substrings from a string in JavaScript. I know it's not correct but I feel like I am going about it the right way. Any advice would be great.
var theString = 'somerandomword',
allSubstrings = [];
getAllSubstrings(theString);
function getAllSubstrings(str) {
var start = 1;
for ( var i = 0; i < str.length; i++ ) {
allSubstrings.push( str.substring(start,i) );
}
}
console.log(allSubstrings)
Edit: Apologies if my question is unclear. By substring I mean all combinations of letters from the string (do not have to be actual words) So if the string was 'abc' you could have [a, ab, abc, b, ba, bac etc...] Thank you for all the responses.
You need two nested loop for the sub strings.
function getAllSubstrings(str) {
var i, j, result = [];
for (i = 0; i < str.length; i++) {
for (j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString));
.as-console-wrapper { max-height: 100% !important; top: 0; }
A modified version of Accepted Answer. In order to give the minimum string length for permutation
function getAllSubstrings(str, size) {
var i, j, result = [];
size = (size || 0);
for (i = 0; i < str.length; i++) {
for (j = str.length; j - i >= size; j--) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString, 6));
Below is a recursive solution to the problem
let result = [];
function subsetsOfString(str, curr = '', index = 0) {
if (index == str.length) {
result.push(curr);
return result;
}
subsetsOfString(str, curr, index + 1);
subsetsOfString(str, curr + str[index], index + 1);
}
subsetsOfString("somerandomword");
console.log(result);
An answer with the use of substring function.
function getAllSubstrings(str) {
var res = [];
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j <= str.length; j++) {
res.push(str.substring(i, j));
}
}
return res;
}
var word = "randomword";
console.log(getAllSubstrings(word));
function generateALlSubstrings(N,str){
for(let i=0; i<N; i++){
for(let j=i+1; j<=N; j++){
console.log(str.substring(i, j));
}
}
}
Below is a simple approach to find all substrings
var arr = "abcde";
for(let i=0; i < arr.length; i++){
for(let j=i; j < arr.length; j++){
let bag ="";
for(let k=i; k<j; k++){
bag = bag + arr[k]
}
console.log(bag)
}
}
function getSubstrings(s){
//if string passed is null or undefined or empty string
if(!s) return [];
let substrings = [];
for(let length = 1 ; length <= s.length; length++){
for(let i = 0 ; (i + length) <= s.length ; i++){
substrings.push(s.substr(i, length));
}
}
return substrings;
}
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.