How to shift except in the first element in array Javascript? - javascript

Initial code: var ar = [1,2,3,4,5,6]
I want to shift starting from second element and add last element. I try to using shift() and splice() but doesn't work and maybe something wrong on my code.
any idea to fix it?
thank you
var ar = [1,2,3,4,5,6];
ar.splice(5,1,"0").shift();
console.log(ar)
expected result [1,3,4,5,6,0]

Maybe a little slice and concat?
var ar = [1,2,3,4,5,6];
var result = ar.slice(0, 1).concat(ar.slice(2)).concat(0)
console.log(result)
Or maybe some destructuring:
const [first, , ...next] = [1,2,3,4,5,6]
console.log([first, ...next, 0])

var ar = [1,2,3,4,5,6];
ar.splice(1,1)
ar.push(0)
console.log(ar)

you can try ES6 rest operator
const array = [1,2,3,4,5]
const [firstItem, ...otherArray] = array
const newArray = [ ...otherArray, 0]
// or direct array assign
// const [firstItem, ...otherArray] = [1,2,3,4,5]
console.log(newArray)

var array = [1, 2, 3, 4, 5, 6];
function shift(arr, start, newElement) {
const arr1 = []
const rest = [];
for (let i = 0; i < start; i++) {
arr1.push(arr[i]);
}
for (let i = start + 1; i < arr.length; i++) {
rest.push(arr[i]);
}
rest.push(newElement)
return [...arr1, ...rest]
}
console.log(shift(array, 1, "0"))
console.log(shift(array, 2, "0"))

Related

How to get the sum of the last index from multiple arrays in javascript

I know this is a very basic question, but I am not able to write the correct code for this. Let's say I have 3 arrays:
arr1 = [1,2,3,4]
arr2 = [5,6,7,8]
arr3 = [7,3,2,1]
I want the sum of the last index, i.e. 4+ 8 + 1 = 13
I am not able to write the correct for loop for the same.
EDIT :
My array is inside an object as shown below:
So, I will have more arrays inside the object. So how do I proceed with this?
let ree = {
arr1: [1, 2, 3, 4],
arr2: [5, 6, 7, 8],
arr3: [7, 3, 2, 1]
};
let total = 0;
for (var key in ree) {
if (Array.isArray(ree[key])) {
total += ree[key][ree[key].length - 1];
}
}
console.log(total);
try this short and easy solution
let arr1 = [1,2,3,4]
let arr2 = [5,6,7,8]
let arr3 = [7,3,2,1]
arrList = [arr1,arr2,arr3]
finalSum = arrList.reduce((acc, cur) => acc+[...cur].pop(), 0)
i created a copy of arrays in reduce as pop modifies original array.
if your array is inside object as key value pair you can get it as array like this
let yourObject = {1:arr1, 2:arr2, 3:arr3}
let arrList = Object.values(yourObject);
an array assigned to a key in an object can be accessed like this
let yourObject = {'somekey':[1,2,3]};
arrList = yourObject.somekey;
console.log(arrList);
You can do something like this using array.length property,
sum = arr1[arr1.length - 1] + arr2[arr2.length - 1] + arr3[arr3.length - 1];
If they are inside another array you can do something like this,
let parentArr = [[1,2,3,4],[5,6,7,8],[7,3,2,1]];
let sum = 0;
for(let i =0;i<parentArr.length; i++) {
sum = sum + parentArr[i][parentArr[i].length - 1];
}
console.log(sum);
If the arrays are inside an object you can do the following,
let parentObj = {'arr1': [1,2,3,4], 'arr2': [5,6,7,8], 'arr3': [7,3,2,1]};
let sum = 0;
let keys = Object.keys(parentObj);
for(let i =0;i<keys.length; i++) {
sum = sum + parentObj[keys[i]][parentObj[keys[i]].length - 1];
}
console.log(sum);
Basic thing to know before we continue :
how many arrays you have ?
can array be empty ?
if number of arrays is static i.e. 3 and they can't be empty then use sabir.alam's
else please define your requirements.
Shorter answer:
const parentArr = [[1,2,3,4],[5,6,7,8],[7,3,2,1]];
const answer = parentArr.map(e=>e[e.length-1]).reduce((x,y)=>x+y);
console.log(answer);

I would like to push a couple of arrays of data into a 2 dimensions array in Javascript

I would like to push a couple of columns of arrays into a 2 dimensions array in Javascript, adding one column in position 0 and the second column at the end of the array.
The initial array is something like this:
[[1,1,1],
[1,1,1],
[1,1,1],
[1,1,1]]
The two arrays I would like to merge with the bidimensional array are:
[0,0,0,0]
and
[2,2,2,2]
The result should be the next:
[[0,1,1,1,2],
[0,1,1,1,2],
[0,1,1,1,2],
[0,1,1,1,2]]
Thanks!
If you are 100% sure that the length of the arrays matches, this can also be solved with a loop as follows:
const arr = [[1,1,1],
[1,1,1],
[1,1,1],
[1,1,1]];
const arrBeg = [0,0,0,0];
const arrEnd = [2,2,2,2];
arr.forEach(function (val, ix) {
val.unshift(arrBeg[ix]);
val.push(arrEnd[ix]);
});
You can use Array#map and spread syntax to add elements to the front and end of each array.
const arr = [[1,1,1],
[1,1,1],
[1,1,1],
[1,1,1]];
const start = [0], //supports adding multiple elements,
end = [2];
const res = arr.map(x => [...start, ...x, ...end]);
console.log(JSON.stringify(res));
You can do it with simple for loop like this:
var arr = [[1,1,1], [1,1,1], [1,1,1], [1,1,1]]
var arr1 = [0, 0, 0, 0];
var arr2 = [2, 2, 2, 2];
var arr1each = 0;
var arr2each = 0;
for (each = 0; each < arr.length; each++) {
arr[each].unshift(arr1[arr1each]);
arr[each].push(arr2[arr2each])
arr1each++;
arr2each++;
continue;
}
console.log(arr)
Here is Codepen
This is basic, but will do for what you want:
function alterArray() {
var testArray = [[1,1,1],[1,1,1],[1,1,1]];
testArray.forEach( arrayElement => {
arrayElement.unshift(0);`
arrayElement.push(2);})
}

Split array into chunks and sum each index, then merge into another array

I am splitting an array into two arrays arr1 & arr2. Then I want to sum the values and bind into another array like arr3. How can I do this?
var arr1 = [1,2,3,4]
var arr2 = [2,3,4,4]
var arr3 = [3,5,7,8]
this works fine with static arrays, but my problem is
var TotalOfArray = [];
var temparray = [];
for (i = 0, j = x.length; i < j; i += chunk) {
temparray = x.slice(i, i + chunk);
if (temparray.length == chunk) {
console.log("before loop: "+TotalOfArray.length);
if (TotalOfArray.length == 0) {
for (i in temparray) {
TotalOfArray[i] = temparray[i];
}
console.log("after loop: "+TotalOfArray.length);
} else {
for (i in temparray) {
TotalOfArray[i] = TotalOfArray[i] + temparray[i];
}
}
}
}
As you can see, x will be the main array which I am splicing into a temparray array, so every time it will splice with array length 31 and than I want to do sum, chunk = 31 as of now. But it's not going into ELSE part.
Equal Length Arrays:
This is just a more simple version, that assumes equal lengths from both arrays. For a solution that works with variable length arrays, read further on.
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 4];
var arr3 = arr1.map(function(a, i) {
return a + arr2[i];
});
console.log(arr3);
Variable Length Arrays:
This is going to be a more robust solution regardless. But it finds the array with the most values in it, and uses that for the map. Then, if undefined values are found in the other array, it will use 0 as the other number.
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 4, 5];
var sorted = [arr1, arr2].sort((a, b) => b.length - a.length);
var arr3 = sorted[0].map(function(a, i) {
return a + (sorted[1][i] || 0);
});
console.log(arr3);
Use for loop:
var arr1 = [1,2,3,4]
var arr2 = [2,3,4,4]
var arr3 = []
for (i in arr1) { arr3[i] = arr1[i] + arr2[i]; }
console.log(arr3)
If two arrays have equal length you can can use Array.prototype.map();
var data1 = [1,2,3,4],
data2 = [2,3,4,4],
result;
result = data1.map(function(value, i){
return value + data2[i];
});
console.log(result);
var arr1 = [1,2,3,4]
var arr2 = [2,3,4,4]
var arr3 = []
for (var i = 0; i < arr1.length; i++) {
arr3.push(arr1[i] + arr2[i])
}
Assuming arr1 and arr2 have the same length.

How to add two arrays in pairwise fashion

I would like to add the values of two JavaScript arrays that have the same length to get a third array so that the the first value of the third array is the sum of the first values of the two first arrays, the second value of the third array is the sum of the second values of the two first arrays, etc. For example:
var array1 = [1,2,3];
var array2 = [4,1,0];
var array3 = array1 + array2;
I would like the result of array3 to be [1+4, 2+1, 3+0] = [5,3,3].
This is not the same question as this. I would like to add the numbers and not make sub-arrays.
I know that you can do for(i = 0; i < array1.length; i++){array3[i] = array1[i] + array2[i]} but I would like to know if there is a built-in code that does this.
Use Array#map() method
var array1 = [1, 2, 3];
var array2 = [4, 1, 0];
var array3 = array1.map(function(v, i) {
return v + array2[i];
})
console.log(array3);
For latest browser use it with ES6 arrow function
var array1 = [1, 2, 3];
var array2 = [4, 1, 0];
var array3 = array1.map((v, i) => v + array2[i])
console.log(array3);
For older browser check polyfill option of map method.
You should use generators.
function *addPairwise(a1, a2) {
let i1 = a1[Symbol.iterator](), i2 = a2[Symbol.iterator](), x1, x2;
while (1) {
x1 = i1.next();
x2 = i2.next();
if (x1.done && x2.done) return;
yield x1.done ? x2.value : x2.done ? x1.value : x1.value + x2.value;
}
}
Normally we would prefer to simply do a for...of loop over an iterable, but there's no way to do that in parallel over two iterables, so we need to get the iterators so we can use the next method on them.
This approach will allow you to do pairwise addition of any iterable including infinite streams.
console.log([...addPairwise([1,2,3], [4,1,0])]);
If you prefer you could define addPairwise to take iterators directly and call it as
addPairwise([1, 2, 3].values(), [4, 1, 0].values())
This assumes suitable support for ES6 such as node v6, Chrome 51, or babel.
var array1 = [1,2,3];
var array2 = [4,1,0];
var array3 = add(array1, array2);
console.log(array3);
function add(arr1, arr2) {
return arr1.map(function(value, index) {
return value + arr2[index];
});
}
For IE8 support:
var array1 = [1,2,3];
var array2 = [4,1,0];
var array3 = add(array1, array2);
console.log(array3);
function add(arr1, arr2) {
var newArray = [];
for(var i = 0; i < arr1.length; i++){
newArray.push(arr1[i] + arr2[i]);
}
return newArray;
}

How to add an element to an array without any built in functions

So I have these two questions considering the JavaScript language:
Is there any way to append to an array without using the push() function or any other built in functions in the language?
Is there any way to merge two arrays together without using the concat() function or any other built in functions in the language?
For the first part you can always use the length property of the array, to add the next element:
a = ['a', 'b', 'c', 'd'];
a[a.length] = 'e';
// a is now ["a", "b", "c", "d", "e"]
To do the latter, merge the arrays, without a function you can just loop thru the arrays, should pick the largest one to loop on. But yeah, as the comments state. There's usually not a good reason to do so.
Here are the alternatives for you:
To add the item to the array without push call:
arr[arr.length] = value;
To concatenate one array to another without concat call:
for (var i = 0; i < arr2.length; arr1[arr1.length] = arr2[i++]);
Not sure if this is what you are looking for or why but arr[arr.length] = 1; is the answer both of your questions.
var myArr = [];
myArr[myArr.length] = 1;
myArr[myArr.length] = 2;
myArr[myArr.length] = 3;
var myArr1 = [...]; // has items;
var myArr2 = [...]; // has items;
var mergedArr = [];
for(var i = 0; i < myArr1.length){
mergedArr[mergedArr.length] = myArr1[i];
}
for(var i = 0; i < myArr2.length){
mergedArr[mergedArr.length] = myArr2[i];
}
Yes, you can do so without using .push, concat, or .length. ES6 allows the use of the spread syntax (...):
var arr = [1, 2]; // arr is 1, 2
var arr = [...arr, 3]; // arr is now 1, 2, 3
let arr1 = [1, 2];
let arr2 = [3, 4];
arr = [...arr1, ...arr2]; // arr is now 1, 2, 3, 4
function pop(arr) {
let finalVar = arr[arr.length - 1];
arr.length = arr.length - 1;
return finalVar;
}
I hope this can solve your problem:
const addItem = (arr, ...arguments) => {
for (let i = 0; i < arguments.length; i++) {
arr[arr.length] = arguments[i];
}
return arr;
};
let myArr = [];
console.log(addItem(myArr, 'Chaewon')); // ['Chaewon'])
console.log(addItem(myArr, 'Liz')); // ['Chaewon', 'Liz']);
<html lang="en">
<head>
<script>
let data = [20, 80, 79, 21, 40];
let newEl = 26;
let position = 2;
console.log(data);
for(let i = data.length-1; i >= 0; i--){
console.log(data[i]);
if (i >= position) {
data[i + 1]= data[i];
if (i === position) {
data[i]= newEl;
}
}
}
console.log(data)
</script>
</head>
<body>
</body>
</html>

Categories