Related
Let's suggest I have an array:
const arr = ['1', '2', '3', '4']
And Object.entries(arr) returns the following: [[0, '1'], [1, '2'], [2, '3'], [3, '4']].
How to convert it back to a normal array? That is:
['1', '2', '3', '4']
Because Object.fromEntries(Object.entries(arr)) returns {0: '1', 1: '2', 2: '3', 3: '4'} -- not what I expected.
UPD
Do not accept answers like Object.values(obj) because sometimes I need a normal key-value object from Object.fromEntries()
You could map
const arr = ['1', '2', '3', '4']
const entries = Object.entries(arr)
console.log(entries)
console.log(entries.map(item => item[1]))
// or
console.log(entries.map(([key,val]) => val))
Use map() to get the second index of each nested array:
const arr = ['1', '2', '3', '4'];
const rra = Object.entries(arr);
const original = rra.map(i => i[1]);
console.log(original);
This question already has answers here:
How to insert an item into an array at a specific index (JavaScript)
(28 answers)
Closed 3 years ago.
I have 2 Javascript arrays:
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
['a', 'b', 'c']
I need to insert elements of second array into the first array every 4th or nth index of the first array, resulting in:
['a', '1', '2', '3', '4', 'b', '5', '6', '7', '8', 'c', '9', '10', '11', '12']
n needs to be a parameter, so I can move n to the 5th location, or 3rd location when needed.
Any solutions appreciated. ES6 ones would be great! Thank you in advance.
You can iterate through the smaller array using forEach use splice() to insert elements.
let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
let arr2 = ['a', 'b', 'c']
function insertArr(arr1,arr2,n){
arr1 = arr1.slice();
arr2.forEach((a,i) => {
arr1.splice(i*n+i,0,a);
})
return arr1;
}
console.log(insertArr(arr1,arr2,4))
Try this
b.forEach((itm, indx) => a.splice(Math.ceil(a.length/b.length)*indx, 0, itm));
Use a forEach with iterator as below:
let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
let arr2 = ['a', 'b', 'c'];
let index = 0;
arr2.forEach(function(v){
arr1.splice(index, 0, v);
index += 5;
});
console.log(arr1);
Now about the ES6, here is how I would write it:
let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
let arr2 = ['a', 'b', 'c'];
let index = 0;
Array.from(arr2).forEach((v)=>{
arr1.splice(index, 0, v);
index += 5;
});
console.log(arr1);
Iterate the 2nd array with Array.flatMap(), take the respective sequence from the 1st array with Array.slice(), and combine it with the current element using spread. Use Array.concat() with slice to add leftover items if any.
const fn = (n, added, target) =>
added.flatMap((el, i) => [el, ...target.slice(n * i, n * (i + 1))])
.concat(target.slice(n * added.length))
const arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
const arr2 = ['a', 'b', 'c']
console.log(JSON.stringify(fn(3, arr2, arr1)));
console.log(JSON.stringify(fn(4, arr2, arr1)));
console.log(JSON.stringify(fn(5, arr2, arr1)));
I try to use an array to iterate all posibilities of combine n element from an array:
array = ["9","0","1","2"];
For example the function combine(array,iter) with iter=2 shuld return:
["90","09","91","19","92","29","01","10","02","20","12","21","99","00","11","22"]
Parameters are define:
array: original array with all elements to combine.
iter: number of elements to result in combine with duplicates.
I try using yield, but without results, the quantity of elements are correct but, the value is wrong:
//Thank you to le_m for the code in ES6!
function* express(tokens, size) {
if (size < 1) yield [];
else
for (var item of tokens) {
for (var combination of express(tokens, size - 1)) {
yield combination.concat(item);
}
}
}
array = ["9","0","1","2"];
for (iter of express(array,2)) {
console.log(iter)
}
Console Output:
[ '9', '9' ]
[ '0', '9' ]
[ '1', '9' ]
[ '2', '9' ]
[ '9', '0' ]
[ '0', '0' ]
[ '1', '0' ]
[ '2', '0' ]
[ '9', '1' ]
[ '0', '1' ]
[ '1', '1' ]
[ '2', '1' ]
[ '9', '2' ]
[ '0', '2' ]
[ '1', '2' ]
[ '2', '2' ]
You want to generate all possible combinations of a given length. There are n^length combinations in total. To avoid the possibly huge memory requirement, I recommend using a generator function:
// Return all combinations of 'length' elements from array:
function* combine(array, length) {
if (length < 1) yield [];
else for (let element of array) {
for (let combination of combine(array, length - 1)) {
yield combination.concat(element);
}
}
}
// Example:
console.log(...combine(["9", "0", "1", "2"], 2));
This question already has answers here:
Split array into chunks
(73 answers)
Closed 5 years ago.
I'm trying to create new array of array from one array,
How to make
var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
become
var array = [['1', '2'], ['3', '4'], ['5', '6'], ['7', '8'], ['9', '10']];
Use a simple loop with Array#splice method to update the same array.
var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
size = 2;
// iterate upto the length(which is dynamic)
for (var i = 0; i < array.length; i++)
// remove the 2 elements and insert as an array element
// at the same index
array.splice(i, 0, array.splice(i, size));
console.log(array);
In case you want to generate a new array then use Array#slice method.
var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
size = 2,
res = [];
// iterate over the array where increment index by the size
for (var i = 0; i < array.length; i += size)
// push the subarray
res.push(array.slice(i, i + size));
console.log(res);
An ES6 alternative with Array.from method:
var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
size = 2;
var res = Array.from({
// create an array of size based on the chunk size
length: Math.ceil(array.length / size)
// iterate and generate element by the index
}, (_, i) => array.slice(i * size, i * size + size))
console.log(res);
Try the following:
var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var newArray = [];
var i,j,chunk = 2;
for (i=0,j=array.length; i<j; i+=chunk) {
newArray.push(array.slice(i,i+chunk));
}
console.log(newArray);
I have been breaking my brain for the last 2 days trying to find a solution to the problem but I can't figure it out.
I need to sort an array of arrays first numerically and then lexicographically. While a custom a < b function can solve the first, a normal array.sort() can do the second. But I have no clue how to combine them.
I have an array similar to this one:
var arr = [
[ '80', '1', '230' ],
[ '9', '1', '230' ],
[ 'Ken', '6', '100' ],
[ 'Dan', '2', '800' ],
[ 'Tom', '6', '500' ],
[ 'team10', '2', '222' ],
[ 'team9', '2', '222' ]
];
This array needs to be sorted numerically first according to the numbers in arr[n][1] (largest to smallest). Results with the same arr[n][1] value need to them be ordered numerically according to arr[n][2] (largest to smallest). And finally results with the same value [n][1] and [n][2] need to be ordered lexigographically based on arr[n][0].
The farthest I have gotten so far is this approach:
function sortArr() {
arr.sort(function(a,b) {
if (a[1] === b[1]) {
if (a[2] === b[2]) {
return b[0] < a[0];
}
return a[2]-b[2];
}
return b[1]-a[1]
});
}
While the numerical sorting works with this, the lexicographical sorting doesn't. Any help would be appreciated.
I suggest to use a chained approach with String#localeCompare for strings.
Sort order:
at index 1 desc
at index 2 desc
at index 0
not nummerical part asc
nummerical part asc
var arr = [[ '80', '1', '230' ], [ '9', '1', '230' ], [ 'Ken', '6', '100' ], [ 'Dan', '2', '800' ], [ 'Tom', '6', '500' ], [ 'team10', '2', '222' ], [ 'team9', '2', '222' ]];
arr.sort(function (a, b) {
var aa = a[0].split(/(\d+)/g),
bb = b[0].split(/(\d+)/g);
return b[1] - a[1] ||
b[2] - a[2] ||
aa[0].localeCompare(bb[0]) || aa[1] - bb[1];
});
console.log(arr);