What's an elegant way to define an array "grouping" utility function? - javascript

Suppose this is my input: "0.1412898495873448 -0.03307049805768848 -0.0002348551519150674 0.0007142371877833145 -0.01250041632738383 0.4052674201000387 -0.02541421100956797 -0.02842612870208528 1803.701163338969 1796.443677744862 1986.31441429052 1442.354524622483"
Sylvester has this constructor. It requires a nested array.
It's simple enough to make the string into an array of numbers using String.split() and map and friends.
Something not unlike this:
var nums = line.split(/ |\n/);
nums.map(function(num) {return parseFloat(num);});
But I think Javascript is missing a functional-style function that can "group" my 16-array into 4 rows of 4 numbers.
I thought maybe a JS utility library such as underscore might have me covered.
Doesn't look like it.
What's the most elegant and/or efficient way to do this? Do I have to use a for loop?
function nest(array, range) {
var l = array.length;
var ret = [];
var cur = null;
for (var i=0; i<l; ++i) {
if (!(i%range)) {
cur = [];
ret.push(cur);
}
cur.push(array[i]);
}
return ret;
}
Node tells me this works:
> function nest(array, range) {
... var l = array.length;
... var ret = [];
... var cur = null;
... for (var i=0; i<l; ++i) {
..... if (!(i%range)) {
....... cur = [];
....... ret.push(cur);
....... }
..... cur.push(array[i]);
..... }
... return ret;
... }
undefined
> nest([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],4)
[ [ 0, 1, 2, 3 ],
[ 4, 5, 6, 7 ],
[ 8, 9, 10, 11 ],
[ 12, 13, 14, 15 ] ]
>
Can anyone think of a better way to do it?

There are several ways to split an array into sub-arrays
var line = "0.1412898495873448 -0.03307049805768848 -0.0002348551519150674 0.0007142371877833145 -0.01250041632738383 0.4052674201000387 -0.02541421100956797 -0.02842612870208528 1803.701163338969 1796.443677744862 1986.31441429052 1442.354524622483";
var nums = line.split(/ |\n/).map(parseFloat);
var columns = 4;
var nested = [];
for (var i=0; i < nums.length; i+=columns) {
nested.push(nums.slice(i, i+columns));
}
console.log(nested);
Or functional way:
var nested = Array.apply(null, new Array((nums.length/columns)|0))
.map(function(item, index) {
return nums.slice(index*columns, (index+1) * columns);
});
Using splice instead of slice seems to be much better, though it might be due to badly written tests
var columns = 4;
var nested = [];
for (var i=nums.length/columns; i--;) { // gives expected result if columns===0
nested.push(nums.splice(0,columns));
}
Alternatively:
var columns = 4;
var nested = [];
while(nums.length) nested.push(nums.splice(0,columns));

Here is my approach,
var nums = line.split(/ |\n/);
var temp=[],output=[],i=0;
while(i<nums.length){
temp.push(i);
if(i%4 == 0){
output.push(temp);
temp=[];
}
i++
}
console.dir(output);
For my senses this is prettty fast!
check this performance test against the accepted answer
http://jsperf.com/comparing-use-of-modulo-vs-slice-in-a-special-case

Related

How to access elements of arrays within array (JavaScript)?

I'm trying to access elements from a JavaScript array:
[["1","John"],["2","Rajan"],["3","Hitesh"],["4","Vin"],["5","ritwik"],["6","sherry"]]
I want to access
1, 2, 3, 4, 5, 6 separately in a variable and John, Rajan, Hitesh, Vin, Ritwik, Sherry separately in a variable.
I tried converting it to a string and split(), but it doesn't work.
this is code i tried
var jArray = <?php echo json_encode($newarray); ?> ;
var nJarr = jArray[0]; nJarr.toString();
var res = nJarr.split(","); var apname = res[0];
alert(apname);
but there's no alert appearing on the screen
If you are open to using Underscore, then it's just
var transposed = _.zip.apply(0, arr);
and the arrays you are looking for will be in transposed[0] and transposed[1].
You can write your own transpose function fairly easily, and it's more compact if you can use ES6 syntax:
transpose = arr => Object.keys(arr[0]).map(i => arr.map(e => e[i]));
>> transpose([["1","John"], ["2","Rajan"], ...]]
<< [[1, 2, ...], ["John", "Rajan", ...]]
If you want an ES5 version, here's one with comments:
function transpose(arr) { // to transpose an array of arrays
return Object.keys(arr[0]) . // get the keys of first sub-array
map(function(i) { // and for each of these keys
arr . // go through the array
map(function(e) { // and from each sub-array
return e[i]; // grab the element with that key
})
))
;
}
If you prefer old-style JS:
function transpose(arr) {
// create and initialize result
var result = [];
for (var i = 0; i < arr[0].length; i++ ) { result[i] = []; }
// loop over subarrays
for (i = 0; i < arr.length; i++) {
var subarray = arr[i];
// loop over elements of subarray and put in result
for (var j = 0; j < subarray.length; j++) {
result[j].push(subarray[j]);
}
}
return result;
}
Do it like bellow
var arr = [["1","John"],["2","Rajan"],["3","Hitesh"],["4","Vin"],["5","ritwik"],["6","sherry"]];
var numbers = arr.map(function(a){return a[0]}); //numbers contain 1,2,3,4,5
var names = arr.map(function(a){return a[1]}); //names contain John,Rajan...
Try this:
var data = [["1","John"],["2","Rajan"],["3","Hitesh"],["4","Vin"],["5","ritwik"],["6","sherry"]];
var IDs = [];
var names = [];
for(i=0; i<data.length; i++)
{
IDs.push(data[i][0]);
names.push(data[i][1]);
}
console.log(IDs);
console.log(names);
Here is the working fiddle.

add elements of an array javascript

Ok, this might be easy for some genius out there but I'm struggling...
This is for a project I'm working on with a slider, I want an array the slider can use for snap points/increments... I'm probably going about this in a mental way but its all good practice! Please help.
var frootVals = [1,2,3,4,5];
var frootInc = [];
for (i=0; i<=frootVals.length; i++) {
if (i == 0){
frootInc.push(frootVals[i]);
}
else{
frootInc.push(frootInc[i-1] += frootVals[i])
}
};
What I'm trying to do is create the new array so that its values are totals of the array elements in frootVals.
The result I'm looking for would be this:
fruitInc = [1,3,6,10,15]
For a different take, I like the functional approach:
var frootVals = [1,2,3,4,5];
var frootInc = [];
var acc = 0;
frootVals.forEach(function(i) {
acc = acc + i;
frootInc.push(acc);
});
var frootVals = [1,2,3,4,5]
, frootInc = [];
// while i < length, <= will give us NaN for last iteration
for ( i = 0; i < frootVals.length; i++) {
if (i == 0) {
frootInc.push(frootVals[i]);
} else {
// rather than frootIne[ i-1 ] += ,
// we will just add both integers and push the value
frootInc.push( frootInc[ i-1 ] + frootVals[ i ] )
}
};
There were a few things wrong with your code check out the commenting in my code example. Hope it helps,
This will do:
var frootVals = [1,2,3,4,5];
var frootInc = [];
for (i=0; i < frootVals.length; i++) { // inferior to the length of the array to avoid iterating 6 times
if (i == 0) {
frootInc.push(frootVals[i]);
}
else {
frootInc.push(frootInc[i-1] + frootVals[i]) // we add the value, we don't reassign values
}
};
alert(JSON.stringify(frootInc));
jsfiddle here: http://jsfiddle.net/f01yceo4/
change your code to:
var frootVals = [1,2,3,4,5];
var frootInc = [frootvals[0]]; //array with first item of 'frootVals' array
for (i=1; i<frootVals.length; i++) {
frootInc.push(frootInc[i-1] + frootVals[i]); //remove '='
}
Here's a very simple pure functional approach (no vars, side-effects, or closures needed):
[1,2,3,4,5].map(function(a){return this[0]+=a;}, [0]);
// == [1, 3, 6, 10, 15]
if you name and un-sandwich the function, you can use it over and over again, unlike a hard-coded var name, property name, or for-loop...

Joining two collections efficiently?

I have run into an issue where I am trying to join two arrays similar to the ones below:
var participants = [
{id: 1, name: "abe"},
{id:2, name:"joe"}
];
var results = [
[
{question: 6, participantId: 1, answer:"test1"},
{question: 6, participantId: 2, answer:"test2"}
],
[
{question: 7, participantId: 1, answer:"test1"},
{question: 7, participantId: 2, answer:"test2"}
]
];
Using nested loops:
_.each(participants, function(participant) {
var row, rowIndex;
row = [];
var rowIndex = 2
return _.each(results, function(result) {
return _.each(result, function(subResult) {
var data;
data = _.find(subResult, function(part) {
return part.participantId === participant.id;
});
row[rowIndex] = data.answer;
return rowIndex++;
});
});
});
This works ok as long as the arrays are small, but once they get larger I am getting huge performance problems. Is there a faster way to combine two arrays in this way?
This is a slimmed down version of my real dataset/code. Please let me know if anything doesn't make sense.
FYI
My end goal is to create a collection of rows for each participant containing their answers. Something like:
[
["abe","test1","test1"],
["joe","test2","test2"]
]
The perf* is not from the for loops so you can change them to _ iteration if they gross you out
var o = Object.create(null);
for( var i = 0, len = participants.length; i < len; ++i ) {
o[participants[i].id] = [participants[i].name];
}
for( var i = 0, len = results.length; i < len; ++i ) {
var innerResult = results[i];
for( var j = 0, len2 = innerResult.length; j < len2; ++j) {
o[innerResult[j].participantId].push(innerResult[j].answer);
}
}
//The rows are in o but you can get an array of course if you want:
var result = [];
for( var key in o ) {
result.push(o[key]);
}
*Well if _ uses native .forEach then that's easily order of magnitude slower than for loop but still your problem is 4 nested loops right now so you might not even need the additional 10x after fixing that.
Here is a solution using ECMA5 methods
Javascript
var makeRows1 = (function () {
"use strict";
function reduceParticipants(previous, participant) {
previous[participant.id] = [participant.name];
return previous;
}
function reduceResult(previous, subResult) {
previous[subResult.participantId].push(subResult.answer);
return previous;
}
function filterParticipants(participant) {
return participant;
}
return function (participants, results) {
var row = participants.reduce(reduceParticipants, []);
results.forEach(function (result) {
result.reduce(reduceResult, row);
});
return row.filter(filterParticipants);
};
}());
This will not be as fast as using raw for loops, like #Esailija answer, but it's not as slow as you may think. It's certainly faster than using Underscore, like your example or the answer given by #Maroshii
Anyway, here is a jsFiddle of all three answers that demonstrates that they all give the same result. It uses quite a large data set, I don't know it compares to the size you are using. The data is generated with the following:
Javascript
function makeName() {
var text = "",
possible = "abcdefghijklmnopqrstuvwxy",
i;
for (i = 0; i < 5; i += 1) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
var count,
count2,
index,
index2,
participants = [],
results = [];
for (index = 0, count = 1000; index < count; index += 4) {
participants.push({
id: index,
name: makeName()
});
}
for (index = 0, count = 1000; index < count; index += 1) {
results[index] = [];
for (index2 = 0, count2 = participants.length; index2 < count2; index2 += 1) {
results[index].push({
question: index,
participantId: participants[index2].id,
answer: "test" + index
});
}
}
Finally, we have a jsperf that compares these three methods, run on the generated data set.
Haven't tested it with large amounts of data but here's an approach:
var groups = _.groupBy(_.flatten(results),'participantId');
var result =_.reduce(groups,function(memo,group) {
var user = _.find(participants,function(p) { return p.id === group[0].participantId; });
var arr = _.pluck(group,'answer');
arr.unshift(user.name);
memo.push(arr);
return memo ;
},[]);
The amounts of groups would be the amount of arrays that you'll have so then iterating over that with not grow exponentially as if you call _.each(_.each(_.each which can be quite expensive.
Again, should be tested.

Getting a union of two arrays in JavaScript [duplicate]

This question already has answers here:
How to merge two arrays in JavaScript and de-duplicate items
(89 answers)
Closed 4 years ago.
Say I have an array of [34, 35, 45, 48, 49] and another array of [48, 55]. How can I get a resulting array of [34, 35, 45, 48, 49, 55]?
With the arrival of ES6 with sets and splat operator (at the time of being works only in Firefox, check compatibility table), you can write the following cryptic one liner:
var a = [34, 35, 45, 48, 49];
var b = [48, 55];
var union = [...new Set([...a, ...b])];
console.log(union);
Little explanation about this line: [...a, ...b] concatenates two arrays, you can use a.concat(b) as well. new Set() create a set out of it and thus your union. And the last [...x] converts it back to an array.
If you don't need to keep the order, and consider 45 and "45" to be the same:
function union_arrays (x, y) {
var obj = {};
for (var i = x.length-1; i >= 0; -- i)
obj[x[i]] = x[i];
for (var i = y.length-1; i >= 0; -- i)
obj[y[i]] = y[i];
var res = []
for (var k in obj) {
if (obj.hasOwnProperty(k)) // <-- optional
res.push(obj[k]);
}
return res;
}
console.log(union_arrays([34,35,45,48,49], [44,55]));
If you use the library underscore you can write like this
var unionArr = _.union([34,35,45,48,49], [48,55]);
console.log(unionArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
Ref: http://underscorejs.org/#union
I'm probably wasting time on a dead thread here. I just had to implement this and went looking to see if I was wasting my time.
I really like KennyTM's answer. That's just how I would attack the problem. Merge the keys into a hash to naturally eliminate duplicates and then extract the keys. If you actually have jQuery you can leverage its goodies to make this a 2 line problem and then roll it into an extension. The each() in jQuery will take care of not iterating over items where hasOwnProperty() is false.
jQuery.fn.extend({
union: function(array1, array2) {
var hash = {}, union = [];
$.each($.merge($.merge([], array1), array2), function (index, value) { hash[value] = value; });
$.each(hash, function (key, value) { union.push(key); } );
return union;
}
});
Note that both of the original arrays are left intact. Then you call it like this:
var union = $.union(array1, array2);
If you wants to concatenate two arrays without any duplicate value,Just try this
var a=[34, 35, 45, 48, 49];
var b=[48, 55];
var c=a.concat(b).sort();
var res=c.filter((value,pos) => {return c.indexOf(value) == pos;} );
function unique(arrayName)
{
var newArray=new Array();
label: for(var i=0; i<arrayName.length;i++ )
{
for(var j=0; j<newArray.length;j++ )
{
if(newArray[j]==arrayName[i])
continue label;
}
newArray[newArray.length] = arrayName[i];
}
return newArray;
}
var arr1 = new Array(0,2,4,4,4,4,4,5,5,6,6,6,7,7,8,9,5,1,2,3,0);
var arr2= new Array(3,5,8,1,2,32,1,2,1,2,4,7,8,9,1,2,1,2,3,4,5);
var union = unique(arr1.concat(arr2));
console.log(union);
Adapted from: https://stackoverflow.com/a/4026828/1830259
Array.prototype.union = function(a)
{
var r = this.slice(0);
a.forEach(function(i) { if (r.indexOf(i) < 0) r.push(i); });
return r;
};
Array.prototype.diff = function(a)
{
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
var s1 = [1, 2, 3, 4];
var s2 = [3, 4, 5, 6];
console.log("s1: " + s1);
console.log("s2: " + s2);
console.log("s1.union(s2): " + s1.union(s2));
console.log("s2.union(s1): " + s2.union(s1));
console.log("s1.diff(s2): " + s1.diff(s2));
console.log("s2.diff(s1): " + s2.diff(s1));
// Output:
// s1: 1,2,3,4
// s2: 3,4,5,6
// s1.union(s2): 1,2,3,4,5,6
// s2.union(s1): 3,4,5,6,1,2
// s1.diff(s2): 1,2
// s2.diff(s1): 5,6
I like Peter Ajtai's concat-then-unique solution, but the code's not very clear. Here's a nicer alternative:
function unique(x) {
return x.filter(function(elem, index) { return x.indexOf(elem) === index; });
};
function union(x, y) {
return unique(x.concat(y));
};
Since indexOf returns the index of the first occurence, we check this against the current element's index (the second parameter to the filter predicate).
Shorter version of kennytm's answer:
function unionArrays(a, b) {
const cache = {};
a.forEach(item => cache[item] = item);
b.forEach(item => cache[item] = item);
return Object.keys(cache).map(key => cache[key]);
};
You can use a jQuery plugin: jQuery Array Utilities
For example the code below
$.union([1, 2, 2, 3], [2, 3, 4, 5, 5])
will return [1,2,3,4,5]
function unite(arr1, arr2, arr3) {
newArr=arr1.concat(arr2).concat(arr3);
a=newArr.filter(function(value){
return !arr1.some(function(value2){
return value == value2;
});
});
console.log(arr1.concat(a));
}//This is for Sorted union following the order :)
function unionArrays() {
var args = arguments,
l = args.length,
obj = {},
res = [],
i, j, k;
while (l--) {
k = args[l];
i = k.length;
while (i--) {
j = k[i];
if (!obj[j]) {
obj[j] = 1;
res.push(j);
}
}
}
return res;
}
var unionArr = unionArrays([34, 35, 45, 48, 49], [44, 55]);
console.log(unionArr);
Somewhat similar in approach to alejandro's method, but a little shorter and should work with any number of arrays.
function unionArray(arrayA, arrayB) {
var obj = {},
i = arrayA.length,
j = arrayB.length,
newArray = [];
while (i--) {
if (!(arrayA[i] in obj)) {
obj[arrayA[i]] = true;
newArray.push(arrayA[i]);
}
}
while (j--) {
if (!(arrayB[j] in obj)) {
obj[arrayB[j]] = true;
newArray.push(arrayB[j]);
}
}
return newArray;
}
var unionArr = unionArray([34, 35, 45, 48, 49], [44, 55]);
console.log(unionArr);
Faster
http://jsperf.com/union-array-faster
I would first concatenate the arrays, then I would return only the unique value.
You have to create your own function to return unique values. Since it is a useful function, you might as well add it in as a functionality of the Array.
In your case with arrays array1 and array2 it would look like this:
array1.concat(array2) - concatenate the two arrays
array1.concat(array2).unique() - return only the unique values. Here unique() is a method you added to the prototype for Array.
The whole thing would look like this:
Array.prototype.unique = function () {
var r = new Array();
o: for(var i = 0, n = this.length; i < n; i++)
{
for(var x = 0, y = r.length; x < y; x++)
{
if(r[x]==this[i])
{
continue o;
}
}
r[r.length] = this[i];
}
return r;
}
var array1 = [34,35,45,48,49];
var array2 = [34,35,45,48,49,55];
// concatenate the arrays then return only the unique values
console.log(array1.concat(array2).unique());
Just wrote before for the same reason (works with any amount of arrays):
/**
* Returns with the union of the given arrays.
*
* #param Any amount of arrays to be united.
* #returns {array} The union array.
*/
function uniteArrays()
{
var union = [];
for (var argumentIndex = 0; argumentIndex < arguments.length; argumentIndex++)
{
eachArgument = arguments[argumentIndex];
if (typeof eachArgument !== 'array')
{
eachArray = eachArgument;
for (var index = 0; index < eachArray.length; index++)
{
eachValue = eachArray[index];
if (arrayHasValue(union, eachValue) == false)
union.push(eachValue);
}
}
}
return union;
}
function arrayHasValue(array, value)
{ return array.indexOf(value) != -1; }
Simple way to deal with merging single array values.
var values[0] = {"id":1235,"name":"value 1"}
values[1] = {"id":4323,"name":"value 2"}
var object=null;
var first=values[0];
for (var i in values)
if(i>0)
object= $.merge(values[i],first)
You can try these:
function union(a, b) {
return a.concat(b).reduce(function(prev, cur) {
if (prev.indexOf(cur) === -1) prev.push(cur);
return prev;
}, []);
}
or
function union(a, b) {
return a.concat(b.filter(function(el) {
return a.indexOf(el) === -1;
}));
}
ES2015 version
Array.prototype.diff = function(a) {return this.filter(i => a.indexOf(i) < 0)};
Array.prototype.union = function(a) {return [...this.diff(a), ...a]}
If you want a custom equals function to match your elements, you can use this function in ES2015:
function unionEquals(left, right, equals){
return left.concat(right).reduce( (acc,element) => {
return acc.some(elt => equals(elt, element))? acc : acc.concat(element)
}, []);
}
It traverses the left+right array. Then for each element, will fill the accumulator if it does not find that element in the accumulator. At the end, there are no duplicate as specified by the equals function.
Pretty, but probably not very efficient with thousands of objects.
I think it would be simplest to create a new array, adding the unique values only as determined by indexOf.
This seems to me to be the most straightforward solution, though I don't know if it is the most efficient. Collation is not preserved.
var a = [34, 35, 45, 48, 49],
b = [48, 55];
var c = union(a, b);
function union(a, b) { // will work for n >= 2 inputs
var newArray = [];
//cycle through input arrays
for (var i = 0, l = arguments.length; i < l; i++) {
//cycle through each input arrays elements
var array = arguments[i];
for (var ii = 0, ll = array.length; ii < ll; ii++) {
var val = array[ii];
//only add elements to the new array if they are unique
if (newArray.indexOf(val) < 0) newArray.push(val);
}
}
return newArray;
}
[i for( i of new Set(array1.concat(array2)))]
Let me break this into parts for you
// This is a list by comprehension
// Store each result in an element of the array
[i
// will be placed in the variable "i", for each element of...
for( i of
// ... the Set which is made of...
new Set(
// ...the concatenation of both arrays
array1.concat(array2)
)
)
]
In other words, it first concatenates both and then it removes the duplicates (a Set, by definition cannot have duplicates)
Do note, though, that the order of the elements is not guaranteed, in this case.

How do I create an Array into another Array?

I have the following JavaScript Array:
var jsonArray = { 'homes' :
[
{
"home_id":"203",
"price":"925",
"sqft":"1100",
"num_of_beds":"2",
"num_of_baths":"2.0",
},
{
"home_id":"59",
"price":"1425",
"sqft":"1900",
"num_of_beds":"4",
"num_of_baths":"2.5",
},
// ... (more homes) ...
]}
I want to convert this to the following type of Array (pseudo code):
var newArray = new Array();
newArray.push(home_id's);
How can I do that?
Notice how the newArray only has home_ids from the big jsonArray array.
Just make a new array and copy the old values in.
var ids = [];
for (var i = 0; i < jsonArray.homes.length; i++) {
ids[i] = jsonArray.homes[i].home_id;
}
Again, jsonArray is not an array but an object, but jsonArray.homes is
var arr = [];
for (var i=0, len = jsonArray.homes.length; i < len; i++){
arr.push(jsonArray.homes[i].home_id);
}
Here's one iterative way:
function getPropertyValues (array, id) {
var result = [];
for ( var hash in array ) {
result.push( array[hash][id]);
}
return result;
}
var home_ids = getPropertyValues(jsonArray.homes, "home_id");
Or if you want to do it real quick and dirty (and you are only targeting modern Javascript capable engines):
var home_ids = jsonArray.homes.map( function(record) { return record.home_id } );

Categories

Resources