Splice strange thing - javascript

I have next code
function doneOrNot(board) {
console.log(board);
let blockNum = [...(board.splice(0, 2))];
return blockNum;
}
console.log(doneOrNot([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
On first console.log I got
(3) [Array(3), Array(3), Array(3)]
0: (3) [7, 8, 9]
length: 1
[[Prototype]]: Array(0)
(Length 3 or 1???)
And on second:
(2) [Array(3), Array(3)]
0: (3) [1, 2, 3]
1: (3) [4, 5, 6]
length: 2
[[Prototype]]: Array(0)
But why array of arrays have changed before (after?) split?

Array splice method, mutates original array and returns removed items.
const arr = [1, 2, 3];
// now arr has 3 elements
const removed_items = arr.splice(0, 2);
// Now removed_items will have [1, 2]
// and arr will have [3]
By the time When you expand on 'console log' in dev tools, the arr has only 1 element. That is reason you are seeing the 1 element.

Related

How can I insert each of an arrays elements every other element in another array? [duplicate]

This question already has answers here:
Merge two arrays with alternating values
(14 answers)
Merge Two Arrays so that the Values Alternate
(6 answers)
interleave mutliple arrays in javascript
(2 answers)
Closed 1 year ago.
I have two arrays.
let a = [1, 3, 5, 7]
let b = [2, 4, 6, 8]
I want the result:
a = [1, 2, 3, 4, 5, 6, 7, 8]
How can I insert each of array B's elements every other element in array A?
I have tried using splice in a for loop, but the length of array A changes so I cannot get it to work.
You can create a new array, loop through a and push the current item and the item in b at the same index:
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let res = []
a.forEach((e,i) => res.push(e, b[i]))
console.log(res)
Alternatively, you can use Array.map and Array.flat:
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let res = a.map((e,i) => [e, b[i]]).flat()
console.log(res)
If the arrays have the same length, then you can use flat map to avoid mutating the original array.
const a = [1, 3, 5, 7];
const b = [2, 4, 6, 8];
const res = b.flatMap((elem, index) => [a[index], elem]);
console.log(res);
You can try:
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8]
let newArray = [...a, ...b]
console.log(newArray) // [1, 3, 5, 7, 2, 4, 6, 8]
If you want to sort just
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8]
let newArray = [...a, ...b].sort((a, b) => a - b)
console.log(newArray) // [1, 2, 3, 4, 5, 6, 7, 8]
Create a new array and flatten it by doing the below.
let a = [1, 3, 5, 7]
let b = [2, 4, 6, 8]
console.log(a.map((e, i)=> [e, b[i]]).flat());
You could transpose the data and get a flat array.
const
transpose = (a, b) => b.map((v, i) => [...(a[i] || []), v]),
a = [1, 3, 5, 7],
b = [2, 4, 6, 8],
result = [a, b]
.reduce(transpose, [])
.flat();
console.log(result);
Don't splice, just create a new array and push them in on every other index.
Do a for loop, and on each loop do
newArrary.push(a[i]);
newArrary.push(b[i]);
You can use reduce
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let c = a.reduce((acc, x, i) => acc.concat([x, b[i]]), []);
console.log(c)
This works for arrays of any length, adapt the code based on the desired result for arrays that are not the same length.
Using forEach and pushing the current element and the relative element from the other array is an option
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let c = [];
a.forEach((x, i) => {c.push(x, b[i])});
console.log(c);
More about forEach - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Splitting nested array to multiple arrays in JavaScript

I have an array like below.
[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]
and I want array like this.
[[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]
here is my approach to get this.
chunk(result, size) {
var finalResluts = result;
for(let j=0; j<result.length; j++){
var k = 0, n = result[j].length;
while (k < n) {
finalResluts[j].push(result[j].slice(k, k += size));
}
}
return finalResluts;
}
console.log(chunk([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]], 3));
result showing as like below. what I am doing wrong here?
0: Array(8)
0: 1
1: 2
2: 3
3: 4
4: 5
5: 6
6: (3) [1, 2, 3]
7: (3) [4, 5, 6]
for reference here is stackblitz https://stackblitz.com/edit/typescript-rmzpby
The problem is that you initialize your finalResults to the input array results, thus the results are pushed into the original [1, 2, 3, 4, 5, 6] array.
What you need to do is create an empty array for each subArray of the input to populate later. Easiest to achieve with map function:
function chunk(result, size) {
//for each subArray - create empty array
var finalResluts = result.map(subArray => []);
for(let j=0; j<result.length; j++){
var k = 0, n = result[j].length;
while (k < n) {
finalResluts[j].push(result[j].slice(k, k += size));
}
}
return finalResluts;
}
console.log(chunk([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]], 3));

How can I convert multidimensional array into 2 dimensions array?

Given multidimensional array (of any size and depth):
const multidimensionalArray = [1, [2, [3, [4, [5]]]], [6], [7, [8], [9]]];
I need to convert it into 2 dimensions array following example below (the idea is that each nested value should be converted into an array of all parents + this value).
Expected 2 dimensions array :
const twoDimensionsArray = [
[1],
[1, 2],
[1, 2, 3],
[1, 2, 3, 4],
[1, 2, 3, 4, 5],
[1, 6],
[1, 7],
[1, 7, 8],
[1, 7, 9],
];
Could you please help me to solve the problem?
A recursive call for each nested array ought to do the trick.
NOTE: The following may not be complete for your use case - your data needs to be in a specific order for this to work - but I think this should be clean enough as an example:
const customFlatten = (arr, parents = [], output = []) => {
for (const item of arr) {
// If not an array...
if (!Array.isArray(item)) {
parents.push(item) // update parents for recursive calls
output.push(parents.slice(0)) // add entry to output (copy of _parents)
// If an array...
} else {
customFlatten(item, parents.slice(0), output) // recursive call
}
}
return output
}
console.log(customFlatten([1, [2, [3, [4, [5]]]], [6], [7, [8], [9]]]))

add/remove elements in array-like object

I have an array-like object:
[1:Array[10], 2: Array[2], 3: Array[2], 4: Array[2], 5: Array[3], 6: Array[1]]
Im trying to remove the first two elements, do some stuff, and then insert them again at the same place.
Here is what i do:
array = Array.prototype.splice.call(array, 0,2);
When logging array in firefox it show this:
Array [ <2 empty slots>, Array[1], Array[2], Array[3], Array[1] ]
Looks good to me,I removed the first two elements and the array now starts with 2 empty slots.
So now, what I hope to do is to add objects to these 2 empty slots.
For simplicity, lets remove to items from the array and then insert them again at the same place:
var twoFirstItems = Array.prototype.slice.call(array, 0,2);
array = Array.prototype.splice.call(array, 0,2);
Now,to re-insert twoFirstItems I would think that I could do:
array.unshift(twoFirstItems)
This does not work as expected, it inserts the array but it does not have a key as it had before its modifikation. I assume this has to do with unshift not working the same with an array-like object as with an array.
So how do you remove/insert elements to an array-like-object properly?
If i do the following:
console.log(array);
console.log(typeof array);
The result:
Array [ <1 empty slot>, Array[2], Array[2], Array[2], Array[3], Array[1] ]
object
Without any complications, you can just re-assign the modified array at that index.
var a = [
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6]
]
a[0] = a[0].map((el) => el * 10)
a[1] = a[1].map((el) => el * 20)
console.log(a)

Javascript Sort a hash by values in array

I have a hash like below
a ={
0: [0, "A9"],
2: [0, "A9.4"],
8: [0, "A9.1"],
6: [1, "A9.5"],
5: [0, "A9.2"],
7: [2, "A9.3"]
};
I need a sorted array corresponding to the second element of the array of every Value.
i.e if my array is in the form of a = {key: [value_1_integer, value_2_string]}
I need to sort my hash by value_2_string so result array is
result = [0, 8, 5, 7, 2, 6]
You can apply Array#sort on the keys with a callback which takes the second elements of the property for sorting.
var object = { 0: [0, "A9"], 2: [0, "A9.4"], 8: [0, "A9.1"], 6: [1, "A9.5"], 5: [0, "A9.2"], 7: [2, "A9.3"] },
keys = Object.keys(object).sort(function (a, b) {
return object[a][1].localeCompare(object[b][1]);
});
console.log(keys);

Categories

Resources