I wish to merge two arrays into one, but cant duplicate using datetime, basically cant merge two results from both arrays with the same datetime.
In each array, the datetime is never repeated.
Both arrays have the same structure, with the same exact positions.
Each array have +60 sub arrays.
example:
Array1 = [[a,b,0000-00-00 00:00],[c,d,0000-00-00 00:59],[e,f,0000-00-00 00:10]];
Array2 = [[z,x,0000-00-00 00:00],[h,s,0000-00-00 00:49],[e,f,0000-00-00 00:20]];
Array12 = [[a,b,0000-00-00 00:00],[c,d,0000-00-00 00:59],[e,f,0000-00-00 00:10],[h,s,0000-00-00 00:49],[e,f,0000-00-00 00:20]];
How can i make this work? I tried a lot of functions, but cant get this working.
Thanks.
If I'm correct you are trying to merge the arrays based in timestamps. Try out this fiddle
var Array1 = [
['a', 'b', '0000-00-00 00:00'],
['c', 'd', '0000-00-00 00:59'],
['e', 'f', '0000-00-00 00:10']
];
var Array2 = [
['z', 'x', '0000-00-00 00:00'],
['h', 's', '0000-00-00 00:49'],
['e', 'f', '0000-00-00 00:20']
];
function mergeArrays(arr1, arr2) {
var merger = {};
for (var i = 0; i < arr1.length; i++) {
merger[arr1[i][2]] = [arr1[i][0], arr1[i][1], arr1[i][2]];
}
for (var i = 0; i < arr2.length; i++) {
if (!(arr2[i][2] in merger)) {
merger[arr2[i][2]] = [arr2[i][0], arr2[i][1], arr2[i][2]];
}
}
var output = [];
for (var key in merger) {
output.push(merger[key]);
}
return output;
}
var result = mergeArrays(Array1, Array2);
console.log(result);
Related
To make one array by randomly scattering items of two ordered arrays, while in the new array A is still before B, p before q, etc.
How to do it? I can use underscorejs or jquery.
[A,B,C,D]
[p,q,r,s]
==>
[p,q,A,r,B,C,D,s], or [A,B,p,C,q,r,s,D] or [A,p,q,B,r,C,s,D] or...
The following is not OK.
[B,p,A,...] or [p,A,r,...]
Your question contains the answer how to do it.
Take a random array.
Move the first element from it to the resulting array.
Repeat until all elements are moved.
One of possible solutions:
var a = ['A', 'B', 'C', 'D'], b = ['p', 'q', 'r', 's'], c = [];
while (a.length||b.length) {
var r = Math.random()+.5|0;
c.push([a, b][r].shift()||[a, b][+!r].shift());
}
console.log(JSON.stringify(c))
Vanilla js in the end.
var cap = ['A','B','C','D'];
var small = ['p','q','r','s'];
var arr = [];
var length = cap.length + small.length;
for(var i=0; i<length; i++) {
var rand = Math.random()-0.5;
var cond = rand > 0;
var pick;
if ( cap.length == 0 ) { pick = small; }
else if ( small.length == 0 ) { pick = cap; }
else { pick = cond ? cap : small; }
arr.push( pick.shift() );
}
With underscore, you can make use of sample for the general case (i.e. any number of arrays):
function mix(...arrays) {
var res = [];
while (_.some(arrays, a => a.length)) {
res.push(_.sample(_.filter(arrays, a => a.length)).shift());
}
return res;
}
console.log(mix(['A', 'B', 'C', 'D'], ['p', 'q', 'r', 's'], [1, 2, 3, 4, 5]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
I have 2 arrays. I am trying to return the similar values between the 2 but in the order of the second. For example, take a look at the two arrays:
array1 = ['a', 'b', 'c']
array2 = ['b', 'c', 'a', 'd']
What I would like to return is this:
sim = ['b', 'c', 'a']
Here is a link to what I am trying to accomplish. Currently the script is faulty and not catching the corner case.
You could use a Set for array1 use Array#filter array2 by checking the set.
var array1 = ['a', 'b', 'c'],
array2 = ['b', 'c', 'a', 'd'],
theSet = new Set(array1),
result = array2.filter(v => theSet.has(v));
console.log(result);
Some annotations to your code:
function arr_sim (a1, a2) {
var //a = {}, // take an object as hash table, better
a = Object.create(null), // a really empty object without prototypes
sim = [],
i; // use single declaration at top
for (i = 0; i < a1.length; i++) { // iterate all item of array 1
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
sim.push(a2[i]); // just push the value
}
}
return sim;
}
console.log(arr_sim(['a', 'b', 'c'], ['b', 'c', 'a', 'd']));
You can iterate array2 with a filter, and check if the value is contained in array1:
let array1 = ['a', 'b', 'c'];
let array2 = ['b', 'c', 'a', 'd'];
let sim = array2.filter((entry) => {
return array1.includes(entry);
});
console.log(sim);
I think this is what you are looking for?
function arr_sim (a1, a2) {
a1 = Array.isArray(a1)?a1:typeof a1 == "string"?a1.split(""):false;
a2 = Array.isArray(a2)?a1:typeof a2 == "string"?a2.split(""):false;
if(!a1 || !a2){
alert("Not valid values");
return;
}
var filterArray = a1.filter(function(val){
return a2.indexOf(val) !== -1;
})
return filterArray;
}
console.log(arr_sim(['a', 'b'], ['b', 'a', 'c', 'd']));
console.log(arr_sim("abcd", "abcde"));
console.log(arr_sim("cxz", "zcx"));
Try this
const arr_sim = (a1, a2) => a2.filter(a => a1.includes(a))
console.log(arr_sim(['a', 'b', 'c'], ['b', 'c', 'a', 'd']));
try this example here similar-values betwe
en two arrays
var a1 = ['a' ,'b'];
var a2 = ['a' ,'b' ,'c'];
var result = arr_sim(a1,a2);// call method arr_sim
console.log(result);
function arr_sim (a1, a2) {
var similar = [];
for( var i = 0 ; i <a1.length ; i++ ){ // loop a1 array
for( var j = 0 ; j <a2.length ; j++ ){ // loop a2 array
if( a1[i] == a2[j] ){ // check if is similar
similar.push(a1[i]); // add to similar array
break; // break second loop find that is similar
} // end if
} // end second lopp
} // end first loop
return similar; // return result
} // end function
Trying to manipulate this:
input = [
[ ['a','b'], ['c','d'], ['e','f'] ],
[ ['g','h'], ['i','j'], ]
]
to
output = [
{a: 'b', c: 'd', e: 'f'},
{g: 'h', i: 'j'},
]
Here's what I have so far:
function transform(array) {
result = [];
for (var i=0; i<array.length; i++){
for (var j=0; j<array[i].length; j++){
// How can I create an object here?
object.array[i][j][0] = array[i][j][1];
}
}
return result;
}
I'm trying to solve this as a coding challenge so I don't necessarily want the answer but I'm unsure of how to proceed. Since the number of arrays that have a pair of strings inside is not uniform (for instance, first set of arrays within the input array has 3 sets, and the second set has 2 sets, I reckon I need to dynamically create objects within each loop that I can add to the results array at the end. How can I do this?
I don't think I'm supposed to use any sort of fancier / higher order functions. The goal is to build up my familiarity with the fundamentals.
You can use reduce to process the outer and inner arrays, e.g.
var input = [
[['a','b'], ['c','d'],['e','f'] ],
[['g','h'], ['i','j'],]
];
// For each outer array
var result = input.reduce(function(acc, a){
// Create an object from the inner arrays
acc.push(a.reduce(function(acc, a) {
acc[a[0]] = a[1];
return acc;
},{}));
return acc;
}, []);
console.log('With reduce\n');
console.log(result);
// Same algorithm using for loops:
var result2 = [];
// For each outer array
for (var i=0, iLen=input.length; i<iLen; i++) {
var acc = {};
var a = input[i];
// Loop over the inner arrays to build an object,
// then push into result array
for (var j=0, jLen=a.length; j<jLen; j++) {
var b = a[j]
acc[b[0]] = b[1];
}
result2.push(acc);
}
console.log('\nWith loops')
console.log(result2);
Input.reduce((memo,num) => {
memo[num[0]]=num[1];
return memo;
},{})
You can use nested for..of loops to iterate each inner array, create object, set property to element at index 0, value to element at index 1, push object to array at completion of nested for..of loop
let input = [
[
['a', 'b'],
['c', 'd'],
['e', 'f']
],
[
['g', 'h'],
['i', 'j']
]
];
let output = [];
for (let arr of input) {
let o = {};
for (let [key, value] of arr) {
o[key] = value;
}
output.push(o);
}
console.log(output);
I have two arrays like this:
const a = ['a', 'b', 'c', 'd'];
const b = ['1', '2', '3', '4'];
I'm trying to make a new array like this:
const c = ['a1', 'b2', 'c3', 'd4'];
I tried it this way:
const c = [];
c.push([`${a[0]}${b[0]}`, `${a[1]}${b[1]}`, `${a[2]}${b[2]}`, `${a[3]}${b[3]}`]);
With actually looping through data and doing this took 17400ms.
I took out the c.push([........]); and it dropped to 1250ms.
Why does this take so long to do?
And what is the best way to do this?
you can use .map to achieve that. map a, then use index on each loop to get element of b.
const a = ['a', 'b', 'c', 'd'];
const b = ['1', '2', '3', '4'];
var c = a.map(function (d, i) {
return d + String(b[i])
})
console.log(c)
// ["a1", "b2", "c3", "d4"]
cleaner code using es6:
var c = a.map((d, i) => `${d}${b[i]}`)
A simple loop.
const a = ['a', 'b', 'c', 'd', 'e'];
const b = ['1', '2', '3'];
var result = [];
for (var i = 0; i < a.length; i++) {
result[i] = a[i] + b[i];
}
alert(result);
As I suspected and you confirmed, the real problem is that you do too many push.
push modifies the length of the array. The specification does not enforce any data structure for arrays, but for non-sparse ones, implementations usually use lists which store the values consecutively in memory. That's problematic when you change the length of the array, because the additional data could not fit in the place in memory where the data currently is, so all data must be moved. push ends up being constant in amortized time instead of just constant.
However, if you know the length of the resulting array beforehand, it's usually better to preallocate.
Then, instead of
var array = [];
for(var i=0; i<2e4; ++i)
array.push([a[0]+b[0], a[1]+b[1], a[2]+b[2], a[3]+b[3]]);
I would use
var array = new Array(2e4);
for(var i=0; i<2e4; ++i)
array[i] = [a[0]+b[0], a[1]+b[1], a[2]+b[2], a[3]+b[3]];
I am trying to generate n arrays with a for loop and push an extra element from another array of n using for loop to each of these arrays.
var userlist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'];
var selectlist = ['c', 'f', 'k'];
get_field_options = userlist.filter(function (el) {
return selectlist.indexOf(el) < 0;
});
var selectlen = selectlist.length;
var op_arr = new Array();
for (var i = 0; i < selectlen; i++) {
op_arr[i] = new Array();
op_arr[i] = get_field_options;
op_arr[i].push(selectlist[i]);
console.log(op_arr[i]);
}
here is my working fiddle.
but its adding items to same array each time. what I am doing wrong?
this line op_arr[i] = get_field_options; makes your arrays reference to the same object.
You need to clone get_field_options to get a new array.
One simple way to clone is to use JSON.stringify like this.
op_arr[i] = JSON.parse(JSON.stringify(get_field_options));
Yet another way, use map and concat functions
var op_arr = selectlist.map(function(el){
return get_field_options.concat(el);
});