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)
Related
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.
I have 10 arrays of data that look like this:
var arr = [1,2,3,4,5,6,7,8,9,10]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9']
...8 More Arrays
Each array will have exactly the same number of elements every time. I wanted to know the best way to generate an array of objects that look like this that combines the various arrays:
overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]
I recognize that I can use a large number of for loops but am looking for a more optimized solution that someone might have.
This is where Array.map() will be your friend. You can iterate through any of the arrays (since they have the same number of elements) and then access each element by index to get the corresponding value for each array in your dataset, like so:
var arr = [0,1,2,3,4,5,6,7,8,9]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'];
var arr3=['foo','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9'];
let mapped = arr.map((elem, index) => {
return {
arr1: arr[index],
arr2: arr2[index],
arr3: arr3[index]
}
});
console.log(mapped);
Edit: If you wanted to access them generically, you can add all of your arrays to one dictionary and iterate over the key/value pairs, like so:
var arr = [0,1,2,3,4,5,6,7,8,9]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'];
var arr3=['foo','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9'];
// combine all arrays into single dataset
let data = {arr, arr2, arr3};
let mapped = arr.map((elem, index) => {
// iterate over the key/value pairs of the dataset, use the key to generate the
// result object key, use the value to grab the item at the current index of the
// corresponding array
return Object.entries(data).reduce((res, [key, value]) => {
res[key] = value[index];
return res;
}, {});
});
console.log(mapped);
Assuming arr1,arr2 are not desired names of resulting object properties, if you need something
that scales nicely for arbitrary number of data arrays
assigns arbitrary key names (not necessarily corresponding to array variable names, or, worse, property name(s) that can't be valid variable name are needed)
works muuuch faster than accepted solution ;)
You may do the following:
const arr1 = [1,2,3,4,5,6,7,8,9,10],
arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'],
keyNames = ['id', 'greeting'],
group = (...arrays) => (keys) =>
arrays.reduce((res, arr, idx) =>
(arr.forEach((e,i) => res[i][keys[idx]] = e), res),
Array.from({length:arrays[0].length}, () => ({}))
)
console.log(group(arr1,arr2)(keyNames))
.as-console-wrapper {min-height:100%;}
Just iterate all arrays with 1 loop counter:
var dataArrayOne = [1, 2, 3, 4 ];
var dataArrayTwo = ["hello", "hello1", "hello2", "hello3" ];
...
var resultArray = [];
for (var i = 0; i < 4; i++)
{
var combined = {
arr1: dataArrayOne[I],
arr2: dataArrayTwo[i]
...
};
resultArray.push(combined);
}
You can get from this:
[ [1, 2, 3]
, [4, 5, 6]
, [7, 8, 9]
]
to this:
[ [1, 4, 7]
, [2, 5, 8]
, [3, 6, 9]
]
with this function:
const combine =
(...arrs) =>
[ arrs.map(xs => xs[0])
, ... ( arrs.every(xs => xs.length === 1)
? []
: combine(...arrs.map(xs => xs.slice(1)))
)
];
combine
( [1, 2, 3]
, [4, 5, 6]
, [7, 8, 9]
);
Then from this:
[ [1, 4, 7]
, [2, 5, 8]
, [3, 6, 9]
]
to this:
[ {arr1: 1, arr2: 4, arr3: 7}
, {arr1: 2, arr2: 5, arr3: 8}
, {arr1: 3, arr2: 6, arr3: 9}
]
with this function:
const to_obj =
(...arrs) =>
arrs.map(arr =>
Object.fromEntries(
arr.map((x, i) => [`arr${i+1}`, x])));
to_obj
( [1, 4, 7]
, [2, 5, 8]
, [3, 6, 9]
)
Hopefully connecting the two functions together is straightforward.
A note about performance
With exactly 10 arrays of 10 elements each, it is unlikely that you can tell whether a particular solution performs better than another. You should probably go for the solution that feels right in terms of readability or maintenance.
By these criteria you should probably exclude mine; just wanted to share a different approach.
Application of 'sortBy' producing unexpected results.
I've gotta be doing something stoopid. This is such a basic operation.
const input = [4,3,2,1];
const sort = list => R.sortBy(R.ascend(R.identity))(list);
console.log(sort(input)); // [ 4, 3, 2, 1 ]
I would expect the output of the 'console.log' invocation to be [ 1, 2, 3, 4 ], but it is not: the output is [ 4, 3, 2, 1 ], same as the input. What am I doing wrong?
As pointed out by Aadit M Shah in the comments you're not using sortBy correctly.
Here's quick overview of how to sort in Ramda:
sort
Returns a copy of the list, sorted according to the comparator function, which should accept two values at a time and return a negative number if the first value is smaller, a positive number if it's larger, and zero if they are equal.
One case use subtract to sort in ascending order:
sort(subtract, [4, 1, 2, 3]);
//=> [1, 2, 3, 4]
Or to sort in descending, just flip it:
sort(flip(subtract), [4, 1, 2, 3]);
//=> [4, 3, 2, 1]
sort simply expects a function that can accept two parameters which can be compared with < or >.
So how would you sort an array of strings? Strings can be compared with < or > but using subtract wouldn't make sense. This is where ascend (or descend) can be useful:
Makes an ascending comparator function out of a function that returns a value that can be compared with < and >.
sort(ascend(identity), ["b", "a", "B", "A"]);
//=> ["A", "B", "a", "b"]
And if you want to make a case insensitive comparison:
sort(ascend(toLower), ["b", "a", "B", "A"]);
//=> ["a", "A", "b", "B"]
sortBy
As we saw, sort expects that you supply it with a function that accepts two parameters that can be compared together using < or >. Numbers and strings can be compared with these operators so if you can give them to Ramda directly then:
sortBy(identity, [4, 1, 2, 3]);
//=> [1, 2, 3, 4]
is the same as:
sort(subtract, [4, 1, 2, 3]);
//=> [1, 2, 3, 4]
However as far as I can tell, sortBy will always sort things in ascending order.
sortWith
You use sortWith when you can have multiple sort criteria:
Sort by age in ascending order
Sort by name in descending order
sortWith([ascend(prop('age')), descend(prop('name'))], [
{age: 40, name: 'John'},
{age: 40, name: 'Zack'},
{age: 10, name: 'Liam'},
{age: 20, name: 'Bill'}
]);
//=> [
//=> {age: 10, name: "Liam"},
//=> {age: 20, name: "Bill"},
//=> {age: 40, name: "Zack"},
//=> {age: 40, name: "John"}
//=> ]
This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 6 years ago.
I am new in JavasSript.
[Array[1], Array[2], Array[0], Array[4], Array[2], Array[8], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1]]
I have this array of objects. I want to combine all array objects to single array of objects.
How can i do this?
You could use a combination of reduce and concat on your array of arrays
var arrOfArrays = [["a","b"],["C","D"]];
var flattened = arrOfArrays.reduce(function(p,c){
return p.concat(c);
});
console.log(flattened);
You can use concat and reduce
let list = [
[1,2,3],
[4,5,6],
[7,8,9]
];
const concat = (x,y) => x.concat(y);
let result = list.reduce(concat, []);
console.log(result);
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
var myArray = [[1, 4], [2, 4], [3, 4]];
var result = [].concat.apply([], myArray);
console.log(result); // 1, 4, 2, 4, 3, 4
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);