Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have an array which looks like this [1,0,3,0,5,0] what I want is that I want to insert the zero elements the elements of this array [2,4,6] so the complete array should look like this [1,2,3,4,5,6].
let a = [1,0,3,0,5,0]
let b = [2,4,6]
// expected output [1,2,3,4,5,6]
You can also use forEach in this case for a mutating solution:
let a = [1, 0, 3, 0, 5, 0, 7, 0];
let b = [2, 4, 6, 8]
a.forEach((i, j) => {
if (i === 0)
a[j] = b[~~(j / 2)] // integer division
})
console.log(a)
You could take a variable for the index for finding falsy values and insert the replacement value at this index.
let data = [1, 0, 3, 0, 5, 0],
replacements = [2, 4, 6],
i = 0;
for (const value of replacements) {
while (data[i]) i++;
data[i] = value;
}
console.log(data);
For getting a new array, you could map the data array with the replacements.
let data = [1, 0, 3, 0, 5, 0],
replacements = [2, 4, 6],
result = data.map(v => v || replacements.shift());
console.log(result);
Below approach with work:
x = [1,0,3,0,5,0]
y = [2,4,6]
j = 0;
for(i = 0; i < x.length; i ++) {
if(x[i] === 0 && j < y.length)
x[i] = y[j++];
}
console.log(x);
You can do something like this:
const a = [1,0,3,0,5,0];
const b = [2,4,6];
let lastIndex = 0;
for (let i = 0; i < b.length; i++) {
lastIndex = a.indexOf(0, lastIndex);
a[lastIndex] = b[i];
}
console.log(a);
Related
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 1 year ago.
Improve this question
I am trying to find what elements have been moved when comparing two arrays of strings. I want to find the elements that where explicitly moved and not moved as a side effect of other values being moved within the array. Please see example below:
const a = [1, 2, 3, 4, 5, 6];
const b = [1, 5, 6, 2, 3, 4];
findMovedElems(a, b) // returns [5, 6] even though [2, 3, 4,] have changed index too - that was caused as a side effect of 5, 6 being moved.
I didn't tested for others situations (like b with numbers not in a, duplicated numbers, etc.), but works on your example.
var a = [1, 2, 3, 4, 5, 6, 7, 8];
var b = [1, 5, 6, 2, 3, 4, 7, 8];
function findMovedElems(a, b) {
let result = [{"status" : 'OK', "arr" : []}]
// navigate over a and b
for (let i = 0, j = 0; i < a.length && j < b.length; i++, j++) {
if (a[i] === b[j]) {
result[result.length - 1].arr.push(a[i]);
continue;
}
result.push({"status" : 'MOVED', "arr" : [] });
// search for current b char on a
for(let i2 = i ; i2 < a.length; i2++) {
if (a[i2] !== b[j]) {
continue;
}
if (i2 === j) {
// a and b are synchonized again. Reset i and return to main loop
result[result.length - 1].status = 'OK';
j--;// warning: decrementing loop variable
i = j;// warning: changing loop variable
break;
}
// found move. Read from a and b when is equals
for (let i3 = i2; i3 < a.length && j < b.length; i3++, j++/* warning: incrementing other loop variable*/) {
if (a[i3] !== b[j]) {
break;
}
result[result.length - 1].arr.push(a[i3]);
}//for_i3
// Go back, because new array possition was readed, and should be read again on main loop
i--;// warning: decrementing loop variable
j--;// warning: decrementing loop variable
if (i === j) {
result.push({"status" : 'OK', "arr" : [] });
} else {
result.push({"status" : 'MOVED_SIDE_EFFECT', "arr" : [] });
}
break;
}//for_i2
}//for_i
return result;
}
console.log(JSON.stringify(findMovedElems(a, b)));
output:
[{"status":"OK","arr":[1]},{"status":"MOVED","arr":[5,6]},{"status":"MOVED_SIDE_EFFECT","arr":[2,3,4]},{"status":"OK","arr":[7,8]}]
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Suppose I have an array called array
var array = [0, 1, 2, 3, 4];
Now if I want to change a value in array I could do something like
array[0] = 'zero';
But how do I change 'every' value in array EXCEPT for a particular one?
Basically I am looking for a shorthand for this
array[0] = 9;
array[1] = 9;
array[2] = 9;
//array[3] left untouched
array[4] = 9;
Something like
array[all except 4] = 9;
How can this be easily done with javascript?
You can use .map, testing whether the index is 4, and returning either the value at that index, or your chosen new value:
const array = [
0,
1,
2,
3,
4
];
const array2 = array.map((val, i) => i === 3 ? val : 9);
console.log(array2);
If you need to mutate the original array (which usually isn't a great idea), .map won't work because it creates a new array, but you can forEach and reassign:
const array = [
0,
1,
2,
3,
4
];
array.forEach((val, i) => {
if (i !== 3) array[i] = 9;
});
console.log(array);
You can use map() to transform the array:
var array = [0,1,2,3,4];
array = array.map((el, i) => {
if(i != 3) el = 9;
return el;
});
console.log(array);
You can modify the existing array using .forEach() with an if condition inside:
let array = [0, 1, 2, 3, 4],
indexToSkip = 3;
array.forEach((_, i) => {
if(i !== indexToSkip)
array[i] = 9;
});
console.log(array);
you could do a for loop as follows:
for(i=0; i<array.length; i++){
if(i!='insert number in array you dont want to chage'){
some code..
}
}
Using a simple for loop,
var array = [0, 1, 2, 3, 4];
console.log(array)
var ignore = 3;
var replace = 5;
for (var i = 0; i < array.length; i++) {
if (i !== ignore) {
array[i] = replace;
}
}
console.log(array)
You could use Array#fill and save the value ath the given index and restore this value.
This approach mutates the given array, as wanted.
const fill = (array, all, save) => (value => (array.fill(all)[save] = value, array))(array[save]);
var array = [0, 1, 2, 3, 4];
console.log(array);
fill(array, 9, 3);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have two arrays as below:
var arr1 = [1,2,3,8,7,5,7,2,9,0];
var arr2 = [8,7,5];
I want to compare arr2 with arr1, when it will find arr2 exactly in the same sequence as it is then it should return true. i.e. if [8,7,5] is found exactly same sequence in arr1 then it will return true.
Note:
We have to do this without using indexOf.
You could use a combination of Array#some and Array#every.
var array1 = [1, 2, 3, 8, 7, 5, 7, 2, 9, 0],
array2 = [8, 7, 5],
result = array1.some(function (a, i, aa) {
return array2.every(function (b, j) {
return aa[i + j] === b;
});
});
console.log(result);
You can loop through the largest array. On each iteration, compare the next values to all of the values found in the smaller array. If they all match, then it contains the smaller array.
var arr1 = [1,2,3,8,7,5,7,2,9,0];
var arr2 = [8,7,5];
console.log(doesArrayContain(arr2, arr1));
function doesArrayContain(smallestArray, biggestArray) {
for (var i = 0; i < biggestArray.length; i++) {
var doesMatch = true;
for (var j = 0; j < smallestArray.length; j++) {
if (biggestArray[i + j] !== smallestArray[j]) {
doesMatch = false; break;
}
}
if (doesMatch) {
return true;
}
}
return false;
}
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();
This question already has answers here:
Convert simple array into two-dimensional array (matrix)
(19 answers)
Closed 8 years ago.
I am working on a program where I have to read the values from a textfile into an 1D array.I have been succesfull in getting the numbers in that 1D array.
m1=[1,2,3,4,5,6,7,8,9]
but I want the array to be
m1=[[1,2,3],[4,5,6],[7,8,9]]
You can use this code :
const arr = [1,2,3,4,5,6,7,8,9];
const newArr = [];
while(arr.length) newArr.push(arr.splice(0,3));
console.log(newArr);
http://jsfiddle.net/JbL3p/
Array.prototype.reshape = function(rows, cols) {
var copy = this.slice(0); // Copy all elements.
this.length = 0; // Clear out existing array.
for (var r = 0; r < rows; r++) {
var row = [];
for (var c = 0; c < cols; c++) {
var i = r * cols + c;
if (i < copy.length) {
row.push(copy[i]);
}
}
this.push(row);
}
};
m1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
m1.reshape(3, 3); // Reshape array in-place.
console.log(m1);
.as-console-wrapper { top:0; max-height:100% !important; }
Output:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
JSFiddle DEMO
I suppose you could do something like this... Just iterate over the array in chunks.
m1=[1,2,3,4,5,6,7,8,9];
// array = input array
// part = size of the chunk
function splitArray(array, part) {
var tmp = [];
for(var i = 0; i < array.length; i += part) {
tmp.push(array.slice(i, i + part));
}
return tmp;
}
console.log(splitArray(m1, 3)); // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Obviously there is no error checking, but you can easily add that.
DEMO
There are so many ways to do the same thing:
var m = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var n = [];
var i = 0;
for (l = m.length + 1; (i + 3) < l; i += 3) {
n.push(m.slice(i, i + 3));
}
// n will be the new array with the subarrays
The above is just one.