How to count one array with respect to another Array [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Suppose I have two arrays
parentArry = [1,2,3]
ChildArr = [1,2,3,4,5,6]
I want to pick to element of child array from each counter of parent array.
something like this :
1 - 1,2
2 - 3,4
3 - 5,6
Here what I am trying but it is not working
parentArry = [1,2,3]
ChildArr = [1,2,3,4,5]
for(var i=0; i<parentArry.length; i++){
console.log(ChildArr[i] + "And" + ChildArr[i+1])
}

I believe this is what you're looking for to get your expected output:
parentArry = [1,2,3]
ChildArr = [1,2,3,4,5,6]
for(var i=0; i<parentArry.length; i++){
console.log(ChildArr[i*2] + "And" + ChildArr[i*2+1])
}

What I believe you're looking for is n windows of size m where n is given by the parent array and you are generating windows from the child array.
This question is somewhat vague, but if you must approach this problem using these two arrays as such, you could do something like:
const a = [1, 2, 3];
const b = [1, 2, 3, 4, 5];
let first;
let second;
wsize = 2
for (var i = 0; i < a.length + wsize; i = i + wsize) {
first = b[i]; // could be undefined
second = b[i + 1]; // could also be undefined
if (first !== undefined && second !== undefined) {
console.log(b[i] + " and " + b[i + 1])
} else if (first !== undefined) {
console.log(b[i])
} else break
}
This is clearly an instructional answer. It is verbose and not very elegant. You'll need to be aware that the length of the first array may result in the production of undefined for the values of first and second If the length of the child array is not divisible by length of the parent array or if the parent array is longer than the child array).
There are better solutions for windowing as well which are flexible enough to handle arbitrary window sizes and arbitrary length child arrays.
What would a more elegant solution look like?
const a = [1, 2, 3];
const b = [1, 2, 3, 4, 5];
const wsize = 2;
for (var i = 0; i < a.length + wsize; i = i + wsize) {
console.log(b.slice(i, i + wsize).join(" , "))
}

Here is my guess - it is long winded but can handle the 5 items which were present when I started coding
const parentArry = [1, 2, 3]
const childArr = [1, 2, 3, 4, 5]
let cnt = 0;
parentArry.forEach(item => {
const res = [childArr[cnt]], next = childArr[++cnt];
if (next) res.push(next);
console.log(item,"-",res.join(","));
cnt++;
})

Related

Sort array without any sort methods using JS [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 months ago.
Improve this question
My goal is not to use any Bubble/Section/Insertion/Merge/Quick Sort—nothing built in.
I am trying to figure out how to:
let arr = [2, 8, 7, 3]
for(let i = 0; i < arr.length; i++) {
//here I want to number use numbers as an index let's say: arr[0] is 2 right?
// I want to set number 2 at index 2 - 1
//arr[1] = at index 8 - 1
//arr[2] = at index 7 - 1
//arr[3] = at index 3 - 1
//output will be : arr [2, 3, 7, 8]
//here index of each num ^ ^ ^ ^
// 1 2 6 7
}
here I tried to remove empty items but I lost whole numbers.screenshot
let arr =[1,3,4,5,6]
let copyArr = [...arr]
copyArr[199] = 200
copyArr[149] = 150
console.log(copyArr)
let str = copyArr.toString().replaceAll(',','').split('')
console.log(str,)
// OUTPUT BELOW:
//copyArr:
// [ 1, 3, 4, 5, 6, <144 empty items>, 150, <49 empty items>, 200 ]
//str :
// [
// '1', '3', '4', '5',
// '6', '1', '5', '0',
// '2', '0', '0'
// ]
There's no need to subtract 1. Just assign each value to the corresponding index of the result array. This will work as long as all the values are non-negative integers and there are no duplicates. You don't have to ensure that the starting index is 0, because the step that removes all the empty values will take care of that.
After this, you can use a simple for loop to splice out all the undefined elements that were created in the gaps.
let result = [];
let arr = [2, 8, 7, 3];
for (let i = 0; i < arr.length; i++) {
result[arr[i]] = arr[i];
}
// remove all the empty elements
for (let i = result.length-1; i >= 0; i--) {
if (result[i] === undefined) {
result.splice(i, 1);
}
}
console.log(result);
See Looping through array and removing items, without breaking for loop for why the second loop counts down instead of up.
For your sorting question:
let arr = [2, 8, 7, 3]
// from: https://www.geeksforgeeks.org/bubble-sort-algorithms-by-using-javascript/
// Creating the bblSort function
function bblSort(arr) {
for (var i = 0; i < arr.length; i++) {
// Last i elements are already in place
for (var j = 0; j < (arr.length - i - 1); j++) {
// Checking if the item at present iteration
// is greater than the next iteration
if (arr[j] > arr[j + 1]) {
// If the condition is true then swap them
var temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
}
return arr;
}
console.log(bblSort(arr).map(item => item - 1))

Why do I get different answer when using `++` vs using `+1` [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
let arr = [3, 5, 5];
let map = {};
for (let i of arr) {
if(map[i]){
map[i] = map[i]++ //<== doesn't work correctly with ++
}else{
map[i] = 1
}
}
console.log(map);
//outputs {3: 1, 5: 1}
Code above outputs {3: 1, 5: 1}, which is incorrect. 5 should be 2, not 1
let arr = [3, 5, 5];
let map = {};
for (let i of arr) {
if(map[i]){
map[i] = map[i]+1 // <== here it works correctly with +1
}else{
map[i] = 1
}
}
console.log(map);
//outputs {3: 1, 5: 2}
Code above outputs {3: 1, 5: 2} correct solution, but why the difference between the two solutions? I thought the ++ is equivalent to +1. But map[i]++ and map[i]+1 give different solutions!
++ after a variable by definition adds one to the variable and returns the unchanged value
b=3;
c=b++; //c = 3, b = 4
you can put ++ before a variable to return the value
b=3;
c=++b; //c = 4 b = 4
EDIT: following Randy Casburn's request in the comments, here's a snippet:
var b1 = 3;
var c1 = b1++;
document.getElementById('res1').innerHTML = 'b1 = '+b1+' & c1 = '+c1;
var b2 = 3;
var c2 = ++b2;
document.getElementById('res2').innerHTML = 'b2 = '+b2+' & c2 = '+c2;
<p id="res1"></p>
<p id="res2"></p>
This is because map++ only increments after the line runs, if you use ++map it will increment it before, map + 1 will do the same thing.
let a = 1
let b = 1
console.log(a + b++) // 2
let a = 1
let b = 1
console.log(a + ++b) // 3
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment#description

Swapping values in an array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This function should swap the values in the array A that are at position i and j. For example, if A = [3,2,1,6,4]
swap(A, 2,3) should change A so it is now:
A = [3,2,6,1,4]
we're swapping the 1 at position 2 and the 6 at position 3 so now the 6 is at position 2 and the 1 is at position 3.
Problem is, I do not know how to swap these! (New to programming)
function swap(A, i, j) {
var swap = myArray[j];
myArray[j] = myArray[i];
myArray[i] = swap;
}
const A = [3, 2, 1, 6, 4];
console.log(swap(A, 2, 3))
Just need to pass the array and swapping indexes. You need to get the value at index i and j using array index as myArray[i] or myArray[j]
function swap(myArray, i, j) {
var swap = myArray[j];
myArray[j] = myArray[i];
myArray[i] = swap;
}
const array = [1, 2, 3, 4, 5, 6];
swap(array, 1, 3);
console.log(array)

Why is my attempt to rotate this array in javascript resulting in indexes being skipped [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
let arr = [1, 2, 3, 4, 5]
let steps = 2
let hold = arr
let indlength = arr.length - 1
for (let i = indlength; i > indlength - steps; i--) {
hold.unshift(arr[i])
hold.pop()
}
console.log(hold)
So I am attempting to rotate this array in javascript to the right by 2 rotations. Instead of getting 4,5,1,2,3 I am getting 3,5,1,2,3. I suspect it has something to do with an index being skipped, because if I up the steps to 3, it becomes 1,3,5,1,2. Here is a repl link https://repl.it/#helixlamont/ExoticTealOpengl
The problem is the reference you're keeping when you do this let hold = arr;
You should create a real copy/clone of arr.
An alternative is using the spread-syntax.
let arr = [1, 2, 3, 4, 5],
steps = 2,
hold = [...arr],
indlength = arr.length - 1;
for (let i = indlength; i > indlength - steps; i--) {
hold.unshift(arr[i]);
hold.pop();
}
console.log(hold)
.as-console-wrapper { max-height: 100% !important; top: 0; }
In your code problem is you're using reference of arr in let hold = arr.
Ele's answer has already added a working snippet of your code.
Other way of doing is using splice and concat
let arr = [1,2,3,4,5]
let steps = 2
let part1 = arr.splice(-steps)
console.log(part1.concat(arr))
You code does not work as desired, because you change the index for unshifting the value. It is starting from the last index and going to zero. The result is some missing values.
By taking always the last index, you get the wanted result.
I would not use one array as source and manipulate another array, with the same object reference. For keeping a consistent approach, I would use only one of it.
let arr = [1, 2, 3, 4, 5]
let steps = 2
let hold = arr
let indlength = arr.length - 1
for (let i = indlength; i > indlength - steps; i--) {
console.log(hold.join(' '));
hold.unshift(hold[indlength]); // take the last value and use hold instead of arr
hold.pop();
}
console.log(hold.join(' '));
A siplified version, is to pop (the last value) and unshift it (at the front of the array). The length of the array is constant.
let array = [1, 2, 3, 4, 5],
steps = 2,
i;
for (i = 0; i < steps; i++) {
console.log(array.join(' '));
array.unshift(array.pop());
}
console.log(array.join(' '));
Others have described why your code isn't working. One simple non-mutating alternative is
const rotate = (steps, arr) => arr.slice(-steps).concat(arr.slice(0, -steps))
console.log(rotate(2, [1, 2, 3, 4, 5]))
console.log(rotate(-1, [1, 2, 3, 4, 5]))
If you wanted to rotate in the other direction, you could drop the negation signs.
This would fail if steps is larger than the length of the array. If you want it to keep rotating then, it's not much more difficult:
const rotate = (steps, arr) =>
arr.slice(-(steps % arr.length)).concat(arr.slice(0, -(steps % arr.length)))

Reverse function in 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 6 years ago.
Improve this question
I want to get the reverse of this array, in this case ([4,3,2,1]). The problem is I can use no reverse or other shorcuts.
const ar = [1, 2, 3, 4]
const reverse = function (arr) {
let x = arr;
for(i=0; i<x.length;i++) {
x[x.length-i-1]=x[i];
}
return x;
};
const reversedArray = reverse(ar);
console.log(reversedArray);
I thought it must be working, however when I run I get [ 1, 2, 2, 1 ]
as an output. Which is because when i=1 at the second index there is no longer 3. What can I do?
It's like swapping two variables without using a temp variable
const ar = [1, 2, 3, 4]
const reverse = function (arr) {
let x = arr, len = x.length-1;
for(i=0; i<x.length/2;i++) {
x[i]+=x[len-i];
x[len-i]=x[i]-x[len-i];
x[i]-=x[len-i]
}
return x;
};
const reversedArray = reverse(ar);
console.log(reversedArray);
Here is a simple example. But you can achieve the same result with other methods.
function reverse(array){
var new_array = [];
for(var i = 0; i< array.length; i++){
new_array[i] = array[array.length -i - 1];
}
return new_array;
}
//how to use
reverse([1,2,3,4,5]); //output
You can keep it simple by using a regular for loop, and then just unshifting the values onto a new array:
function reverse(arr) {
let reversed = [];
for (let i = 0; i < arr.length; i++) {
reversed.unshift(arr[i]);
}
return reversed;
}
console.log(reverse([1, 2, 3, 4]));
console.log(reverse([6, 7, 8, 9]));
With a while loop and starting from the end of the array :
var arr = [1, 2, 3, 4];
function arrReverse(arr) {
var res = [];
var max = arr.length - 1;
while (max > -1) {
res.push(arr[max]);
max -= 1;
}
return res;
}
var res = arrReverse(arr);
console.log(res);
You're changing the array while you do that because of Javascript's references.
You can use array.prototype.reverse (which is used as [].reverse())
Or you should set a new array and return it.
Don't use the array as a constant. It is probably not letting you make changes in the array.
Then use the reverse method:
ar.reverse();

Categories