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; }
Related
I want to know how can I add 3 different number to the 3n, 3n+1 and 3n+2 indices. I mean for example I have following array :
var arr = [1,1,1,2,2,2,3,3,3]
and then I want add the (3n)th to 5 and then I want add (3n+1)th of an array to 2 and (3n+2) to 3,
I mean the final array I want to be like following result array:
var result = [6,3,4,7,4,5,8,5,6]
and I try to do it as following code:
// arr = [1,1,1,2,2,2,3,3,3]
let res = [];
for (let i = 0; i < arr.length; i++) {
res.push([arr[i*3] * 5,
arr[(i*3)+1] *2,
arr[(i*3)+2] *3])
}
This should do the trick:
var arr = [1,1,1,2,2,2,3,3,3],
add = [5,2,3], res=[];
// result = [6,3,4,7,4,5,8,5,6]
for (let i=0;i<arr.length;i+=add.length) add.forEach((v,j)=>res[i+j]=arr[i+j]+v);
console.log(JSON.stringify(res))
An alternative and even shorter solution (similar to #Robin's answer) would be:
var arr = [1,1,1,2,2,2,3,3,3],
add = [5,2,3], res=[];
res=arr.map((v,i)=>v+add[i%add.length]);
console.log(JSON.stringify(res))
( I noticed #Nina came up with a very similar answer ...)
You can simply use map, making use of the fact that its function argument takes the current index an optional second argument:
var arr = [1,1,1,2,2,2,3,3,3];
var result = arr.map((num, idx) => {
switch (idx % 3) {
case 0:
return num + 5;
case 1:
return num + 2;
case 2:
return num + 3;
}
});
console.log(result);
You could mapp the array directly by taking a closure over an index for the values array for adding.
var array = [1, 1, 1, 2, 2, 2, 3, 3, 3],
add = [5, 2, 3],
result = array.map((i => v => v + add[i++ % add.length])(0));
console.log(...result);
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);
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
I have this initialArray = [1,2,3,4,5,6]
I want to add this [1,2,3]
1 / If [1,2,3] exists in the initialArray, I want to remove it from initialArray.
So the results will be [4,5,6]
2 / Then I want to add [1,2,3] again, and now [1,2,3] is not exist anymore in that initialArray.
So in that case, results will be [4,5,6,1,2,3]
3 / Now I want to add [1,2,3,4,5,6]. So in that case, results will be []
I tried to use .filter() to remove existing values, and it works. But I can't "concat" if values doesn't exist. I have not been able to do both.
How can I do?
You can use indexOf method, so it might look something like this (basic example to gave you an idea):
var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);
think about this also, code below will acctually check if the value you tried to insert to array exist allready inside, so it will remove it:
for(var i = arrayWithNumbers.length - 1; i >= 0; i--) {
if(arrayWithNumbers[i] === number) {
arrayWithNumbers.splice(i, 1);
}
}
You could iterate the array to add and seach for the index and ither push the value or splice the array.
This solution mutates the original array.
function add(target, source) {
source.forEach(v => {
var p = target.indexOf(v);
if (p === -1) {
target.push(v);
} else {
target.splice(p, 1);
}
});
return target;
}
var array = [1, 2, 3, 4, 5, 6];
add(array, [1, 2, 3]);
console.log(array); // [4, 5, 6]
add(array, [1, 2, 3]);
console.log(array); // [4, 5, 6, 1, 2, 3]
add(array, [1, 2, 3, 4, 5, 6]);
console.log(array); // []
const initialArray = []; // your initial array
const add = []; // stuff you want to add
const { filtered, toAdd } = initialArray.reduce((acc, curr) => {
const index = acc.toAdd.findIndex(v => v === curr);
index === -1 ? acc.filtered.push(curr) : acc.toAdd.splice(index, 1);
return acc;
}, { filtered: [], toAdd: [...add] });
const final = [...filtered, ...toAdd];
And if your initialArray had duplicate values you could just do,
const initialArray = [...new Set(initialArrayWithDuplicates)];
Another way of doing this, mutating the original array could be this:
const initialArray = [1,2,3,4,5,6];
const toggleElements = (array, change) =>
array.toString().includes(change)
? array.splice(array.indexOf(change[0]), change.length)
: array.push(...change);
toggleElements(initialArray, [1,2,3]);
console.log(initialArray);
toggleElements(initialArray, [1,2,3]);
console.log(initialArray);
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();