I have two arrays one with field names and the other array is having a list of arrays where each array corresponds to row in table.How can i use these two arrays to create a list of JSON Objects. Is there any in built function. I am able to acheive this using map/reduce/ for -loop but this is impacting the performance if the second array is having more rows as we have traverse through each row.
I hope the following explains the use case better. Please share the sample code if possible.
Arr1=[field1,field2];
Arr2=[[1,2],[3,4],[5,6]];
Expected Output:
[
{
field1 :1 ,
field2: 2
},
{
field1 :3 ,
field2: 4
},
{
field1 :5 ,
field2: 6
}
]
You can use Array.map to map the elements
const mapFields = (arr1, arr2) => {
const mappedArray = arr2.map((el) => {
const mappedArrayEl = [];
el.forEach((value, i) => {
if (arr1.length < (i+1)) return;
mappedArrayEl[arr1[i]] = value;
});
return mappedArrayEl;
});
return mappedArray;
}
const Arr1 = ["field1","field2"];
const Arr2 = [[1,2],[3,4],[5,6]];
console.log(mapFields(Arr1, Arr2));
Related
I am trying find unique ObjectIds from monogdb ObjectId array using filter. For some reason I am not getting unique array back. Is there is some other way to get unique array back ?
var objIds = [ 5ad3509fbb426a4f4a382754,
5ad3509fbb426a4f4a382752,
5ad3509fbb426a4f4a382754,
5ad3509fbb426a4f4a382751
]
Here is the filter code
objIds = objIds.filter((x, i, a) => a.indexOf(x) == i)
I am expecting following array after filter
[ 5ad3509fbb426a4f4a382754,
5ad3509fbb426a4f4a382752,
5ad3509fbb426a4f4a382751
]
If you are passing in an array and the elements inside the array is a string then this should work.
function getUniqueValues(arr) {
return arr.filter((e, i) => arr.indexOf(e) === i)
}
you can use lodash's uniq method to do this easily.
const { uniq } = require("lodash");
var objIds = [
"5ad3509fbb426a4f4a382754",
"5ad3509fbb426a4f4a382752",
"5ad3509fbb426a4f4a382754",
"5ad3509fbb426a4f4a382751"
];
console.log(uniq(objIds));
will give the following output
[ '5ad3509fbb426a4f4a382754',
'5ad3509fbb426a4f4a382752',
'5ad3509fbb426a4f4a382751' ]
I have applied search filter on a array using this code in my listproduct.ts
if (val && val.trim() != '') {
this.names = this.names.filter((names) => {
return (names.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
Note that this filter is applied on names array. I wish this filter should also work on catg and pservice named arrays too.
How can I achieve filter result on multiple arrays?
You can create another bigArray which is the concatenation of your three arrays using js concat function :
var bigArray = this.names.concat(this.catg, this.pservice);
and call your filter on that bigArray.
var val = "test";
this.names = ["abc", "test123", "test"];
this.catg = ["qsd", "azetest"];
this.pservice = ["another test !", "tss"];
this.bigArray = this.names.concat(this.catg, this.pservice);
// here, bigArray contains all values of the three arrays (abc,test123,test,qsd,azetest,another test !,tss)
if (val && val.trim() != '') {
this.bigArray = this.bigArray.filter((names) => {
return (names.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
// here, bigArray contains only filtered values of the three arrays (test123,test,azetest,another test !)
Here is a working Plunker
If you need to keep them as separate arrays, and cannot concat them, you could do something like this:
let names = ["Andy", "Alex", "Corbyn", "Eric" ];
let catg = ["Adventure", "Action", "Comedy", "SciFi"];
let pservice = ["Example", "Service", "Allo"]
let val = "a";
[names, catg, pservice] = [names, catg, pservice].map(array => {
return array.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
});
console.log(names);
console.log(catg);
console.log(pservice);
I have two arrays that I want to merge together to one array of objects...
The first array is of dates (strings):
let metrodates = [
"2008-01",
"2008-02",
"2008-03",..ect
];
The second array is of numbers:
let figures = [
0,
0.555,
0.293,..ect
]
I want to merge them to make an object like this (so the array items match up by their similar index):
let metrodata = [
{data: 0, date: "2008-01"},
{data: 0.555, date: "2008-02"},
{data: 0.293, date: "2008-03"},..ect
];
So far I do this like so: I create an empty array and then loop through one of the first two arrays to get the index number (the first two arrays are the same length)... But is there an easier way (in ES6)?
let metrodata = [];
for(let index in metrodates){
metrodata.push({data: figures[index], date: metrodates[index]});
}
The easiest way is probably to use map and the index provided to the callback
let metrodates = [
"2008-01",
"2008-02",
"2008-03"
];
let figures = [
0,
0.555,
0.293
];
let output = metrodates.map((date,i) => ({date, data: figures[i]}));
console.log(output);
Another option is to make a generic zip function which collates your two input arrays into a single array. This is usually called a "zip" because it interlaces the inputs like teeth on a zipper.
const zip = ([x,...xs], [y,...ys]) => {
if (x === undefined || y === undefined)
return [];
else
return [[x,y], ...zip(xs, ys)];
}
let metrodates = [
"2008-01",
"2008-02",
"2008-03"
];
let figures = [
0,
0.555,
0.293
];
let output = zip(metrodates, figures).map(([date, data]) => ({date, data}));
console.log(output);
Another option is to make a generic map function which accepts more than one source array. The mapping function will receive one value from each source list. See Racket's map procedure for more examples of its use.
This answer might seem the most complicated but it is also the most versatile because it accepts any number of source array inputs.
const isEmpty = xs => xs.length === 0;
const head = ([x,...xs]) => x;
const tail = ([x,...xs]) => xs;
const map = (f, ...xxs) => {
let loop = (acc, xxs) => {
if (xxs.some(isEmpty))
return acc;
else
return loop([...acc, f(...xxs.map(head))], xxs.map(tail));
};
return loop([], xxs);
}
let metrodates = [
"2008-01",
"2008-02",
"2008-03"
];
let figures = [
0,
0.555,
0.293
];
let output = map(
(date, data) => ({date, data}),
metrodates,
figures
);
console.log(output);
If you use lodash, you can use zipWith + ES6 shorthand propery names + ES6 Arrow functions for a one-liner, otherwise see #noami's answer.
const metrodata = _.zipWith(figures, metrodates, (data, date)=> ({ data, date }));
How can I query by a array with size in a range?
Documents:
Foo { foo_array: [{name: "item_1"},{name: "item_2}] }
Foo { foo_array: [{name: "item_1"}] }
Foo { foo_array: [{name: "item_1"},{name: "item_2},{name: "item_3}] }
For instance, I try to get: Foo objects which foo_array field has between 2 or 3 items.
Something like:
Foo.where(:foo_array.with_size => [2,3])
You can query arrays by index and then check if the element at the desired index exists. For example:
Foo.where(
# something at index 1 means that the size is at least two
'foo_array.1' => { :$exists => true },
# nothing at index 3 means that the size is at most three
'foo_array.3' => { :$exists => false }
)
Can anyone tell me how to compare two arrays and delete the common terms in ActionScript?
Eg:
Array1 = [2,4,6,8,10,12]
Array2 = [1,2,3,4,5,6,7,8,9,10,11]
Array1 - Array2 = [12]
If you use ActionLinq, it is very easy to do set mathematics like this:
var array1:Array = [2,4,6,8,10,12];
var array2:Array = [1,2,3,4,5,6,7,8,9,10,11];
var subtraction:Array = Enumerable.from(array1)
.except(Enumerable.from(array2))
.toArray();
You can filter using a custom function.
This is not an optimized way of filtering a difference of arrays, but it'll get the job done.
subtraction = Array1.filter(function(item:*, index:int, arr:Array){
var i:int;
var l:int;
l = Array2.length;
for ( i=0; i < l; i++ )
{
if ( Array2[i] == item )
{
return false;
}
}
return true;
});
If you wish to knock out all duplicates from an Array then I suggest that you use a Set to make the lookup speed as fast as possible:
const a : Array = [ 2, 3, 4 ];
const b : Array = [ 3, 4, 5 ];
// Create a Set for Array 'b' to provide a fast lookup table.
const setB : Object = {};
var prop : *;
for each (prop in b) {
setB[key] = true
};
// Find all values which only belong in Array 'a'.
const uniqueToA : Array = [];
for each (prop in a) {
if (setB[prop] === undefined) {
uniqueToA.push(prop);
}
}
If you find yourself doing a lot of work with collections then I would advise you invest in a Collections Framework such as AS3Commons Collections.