Related
First of all feel free to edit title if it isn't precise enough.
JS is completly not my territory.
Im trying to write this custom JS callback and, aside of the index-grabing line, it does what i require.
However since im already inside a double for-loop i have no idea how to push correct
( by correct I mean: the indexes under which each occurence of value present in 'active holder' var resided before pushing to 'partial_data' var)
indexes into indexes var. As it looks now, it will only return index of first occurence.
var full_data = ['a', 'b', 'c', 'd', 'a', 'g', 'g', 'h']
var partial_data = []
var active_holder = ['a', 'g']
var indexes = []
for (j = 0; j < full_data.length; j++) {
for (z = 0; z < active_holder.length; z++) {
if (active_holder[z].includes(full_data[j])) {
indexes.push(full_data.indexOf(full_data[j]));
partial_data.push(full_data[j]);
}
}
}
console.log(partial_data) // * ['a', 'a', 'g', 'g'] //
console.log(indexes) // * [0, 0, 5, 5] // WRONG, should be 0,4,5,6 or something along
Any suggestions please ?
You can use reduce and includes
const fullData = ['a', 'b', 'c', 'd', 'a', 'g', 'g', 'h']
const active = ['a', 'g']
let {partial, index} = fullData.reduce((op,inp,index)=>{
if( active.includes(inp) ){
op.partial.push(inp)
op.index.push(index)
}
return op
},{partial:[],index:[]})
console.log(partial)
console.log(index)
You could use reduce method and return one object with both indexes and partial data.
var data = ['a', 'b', 'c', 'd', 'a', 'g', 'g', 'h']
var active = ['a', 'g']
const {
index,
partial
} = data.reduce((r, e, i) => {
if (active.includes(e)) {
r.index.push(i)
r.partial.push(e)
}
return r
}, {
index: [],
partial: []
})
console.log(index)
console.log(partial)
You are again calling indexOf while push(). You should just push() j.
indexOf: returns the index for first occurence of value in array
var full_data = ['a', 'b', 'c', 'd', 'a', 'g', 'g', 'h']
var partial_data = []
var active_holder = ['a', 'g']
var indexes = []
for (j = 0; j < full_data.length; j++) {
for (z = 0; z < active_holder.length; z++) {
if (active_holder[z].includes(full_data[j])) {
indexes.push(j);
partial_data.push(full_data[j]);
}
}
}
console.log(partial_data) // * ['a', 'a', 'g', 'g'] //
console.log(indexes) // * [0, 0, 5, 5] // WRONG, should be 0,4,5,6 or something along
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
Consider the following scenario;
var defaultArr = ['a', 'b', 'c', 'd'];
var availArr = [];
var selectedArr = [];
If I am passing array some index's value in param's, I need to split up my array's
Example:
If Array Index : 0,2
Expected result:
availArr = ['b', 'd'];
selectedArr = ['a', 'c'];
Is there any default method to achieve this?
Failrly easy with Array.reduce
var defaultArr = ['a', 'b', 'c', 'd'];
var indexes = [0,2];
var result = defaultArr.reduce(function(p, c, i){
if(indexes.indexOf(i)>-1)
p.selectedArr.push(c);
else
p.availArr.push(c);
return p;
}, {availArr: [], selectedArr:[]});;
console.log('availArr',result.availArr);
console.log('selectedArr',result.selectedArr);
This works because reduce takes a callback argument which is passed 3 arguments - in my example above
p the seed object passed in
c the current array element
i the index of the current element
And uses that information along with indexOf to determine which result array to push to.
You could use Array#reduceRight and iterate the indices array.
var defaultArr = ['a', 'b', 'c', 'd'],
availArr = defaultArr.slice(),
selectedArr = [],
indices = [0, 2];
indices.reduceRight(function (_, a) {
selectedArr.unshift(availArr.splice(a, 1)[0]);
}, 0);
console.log(availArr);
console.log(selectedArr);
var defaultArr = ['a', 'b', 'c', 'd'];
var availArr = [];
var selectedArr = [];
function splitArray(indexes) {
availArr = defaultArr;
indexes.forEach(function(idx) {
let item = availArr.splice(idx, 1)[0];
selectedArr.push(item);
})
}
splitArray([0, 2]);
console.log(availArr);
console.log(selectedArr);
You can use Array methods like forEach and includes
var given = ['a', 'b', 'c', 'd'];
var indexes = [0, 2];
var available = [];
var selected = [];
given.forEach(function (v, i) {
if (indexes.includes(i)) {
selected.push(v);
} else {
available.push(v);
}
});
document.write(JSON.stringify({
given: given,
available: available,
selected: selected
}));
In JS Array.prototype.reduceRight() is the ideal functor to iterate over an array and to morph it by removing items. Accordingly i would approach this job as follows;
var defaultArr = ['a', 'b', 'c', 'd'],
indices = [0, 2];
result = defaultArr.reduceRight((p,c,i,a) => indices.includes(i) ? p.concat(a.splice(i,1)) : p ,[]);
console.log(defaultArr,result);
You can use array.splice + array.concat to achieve this
var defaultArr = ['a', 'b', 'c', 'd'];
var availArr = [];
var selectedArr = [];
function parseIndexes(indexArr){
var deleteCount = 0;
availArr = defaultArr.map(x=>x);
indexArr.forEach(function(i){
selectedArr = selectedArr.concat(availArr.splice(i-deleteCount,1))
deleteCount++;
});
console.log(availArr, selectedArr)
}
parseIndexes([0,2])
With only Array.filter
var array = ['a', 'b', 'c', 'd'];
var indexes = [0, 2]
array.filter(function(el, i) {
return indexes.indexOf(i) !== -1
});
// ["a", "c"]
With array the array of your elements, objects, strings... and indexes the array containing all the indexes of the elements you want to keep, you just remove from the arrayarray all the elements whose id isn't in theindexes array.
The array of all selected entries can be obtained in one line via the Array.map:
var defaultArr = ['a', 'b', 'c', 'd']
var index = [0,2]
var selectedArr = index.map(i => defaultArr[i]) //=> ['a', 'c']
Then the array of the remaining entries can be retrieved e.g. with the Ramda's difference operator:
var availArr = R.difference(defaultArr, selectedArr) //=> ['b', 'd']
I have four arrays like this
var Broker = ['A', 'B', 'C'];
var Currency = ['C', 'D', 'E'];
var Time = ['F', 'G', 'H', 'I'];
var Mode = ['J', 'K', 'L'];
so all theses arrays are shown in multiple select separtely.so when user selects the multiple field from each multi select dropdown i like to list all the paring possiblities with selected items
exampleif user choose A and B from Broker, C from currency, F,G from time and J from mode the paring possiblity should be stored in another separate array like this
var paired = [{borker:A,currency:C,time:F, mode: J},{borker:A,currency:C,time:G, mode: J},{borker:A,currency:C,time:F, mode: J}, {borker:B,currency:C,time:F, mode: J},{borker:B,currency:C,time:G, mode: K},{borker:B,currency:C,time:F, mode: L}];
I may missed the items in paried array but i need atleast one unique item from all the selected arrays.Its kind of set.So can you guys how can i obtain this kind of result.
This code creates an array called permutations which holds an object for every possible permutation of choices. The nested for-loops are the trick to permutations.
var Broker = ['A', 'B', 'C'];
var Currency = ['C', 'D', 'E'];
var Time = ['F', 'G', 'H', 'I'];
var Mode = ['J', 'K', 'L'];
var permutations = [];
for(var i = 0; i < Broker.length; i++) {
for(var j = 0; j < Currency.length; j++) {
for(var k = 0; k < Time.length; k++) {
for(var l = 0; l < Mode.length; l++) {
permutations.push({
borker:Broker[i],
currency:Currency[j],
time:Time[k],
mode:Mode[l]
});
}
}
}
}
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);