I have two array. I want to merge this two arrays into one array. One array consisting keys and another one values.My array looks like
productId = [8,7,9];//Key Element
quantity = ["5","1","3"];//Value Element
//expected new array
newarray = {
"8": 5,
"7": 1,
"9": 3
}
I already tried to merge these arrays, in this way
var newArray = {};
for(var i=0; i< productId.length; i++){
newArray[productId[i]] = quantity [i];
}
console.log(newArray);
It returns
Object [ <7 empty slots>, "5", "1", "3" ]
You are working in firefox so you may get this type of issue because the problem might be caused at how Firefox' console.log has interpreted the input object.
Please look here
Empty slots in JavaScript objects?
Try this
var productId = [8,7,9];
var quantity = ["5","1","3"];
var newarray = {};
productId.forEach((key, i) => newarray[key] = quantity[i]);
console.log(newarray);
Try the following:
var productId = [8,7,9];//Key Element
var quantity = ["5","1","3"];//Value Element
var obj = {};
var i = 0;
for(var k of productId) {
obj[k] = parseInt(quantity[i]);
i++;
}
console.log(obj);
Your new "array" is not an Array but an Object.
You can iterate on one of the arrays using Array.reduce to construct the object.
Something like that:
const arr1 = ['8', '2', '4'];
const arr2 = ['28', '12', '45'];
const result = arr1.reduce((obj, currentItem, index) => {
obj[currentItem] = arr2[index];
return obj;
}, {});
console.log(result);
Related
I have two arrays like:
arr1 = ["orange","banana"]
arr2 = [{"fruit"= ["pineapple","banana"]},{"fruit"= ["grapes","apple"]},{"fruit"= ["apple","orange"]}]
And i need to filter if in second array exists an item of the first.
I am trying to do this:
let kFilter = arr1.map(itemY => { return itemY; });
let filteredK = arr2.filter(itemX => kFilter.includes(itemX.fruit));
But no success :-(
First to avoid too much iteration convert the simple array to an object something like following. Otherwise the complexity will be high
const fruitMap = {
"orange": 1,
"banana": 1
};
Then you have to iterate over each of the items in second array
arr2.forEach(fruitsObj => {
let arr = fruitsObj['fruit'];
for (let i = 0; i < arr.length(); i ++) {
if (fruitMap[arr[i]]) {
arr.splice(i, 1);
}
}
})
//declaration variables correctly
let arr1 = ["orange","banana"]
let arr2 = [{"fruit" : ["pineapple","banana"]},{"fruit" : ["grapes","apple"]},{"fruit": ["apple","orange"]}];
//filter using reduce
arr2.filter((e)=>arr1.reduce((a,i)=>a||e["fruit"].includes(i),false))
//filter using some
arr2.filter((e)=>arr1.some((i)=>e["fruit"].includes(i)))
I am trying to iterate array of objects with different properties. where I am adding objects dynamically and want to check whether the property of the object is exist in the array then only override the value else add it to the array.
For e.x.
var arr = [
{"value":"abc"},
{"type":"def"},
{"status":"ghi"},
{"value":"xyz"}
]
expected result:
arr = [
{"value":"xyz"},
{"type":"def"},
{"status":"ghi"}
]
What I am trying so far is not working. Here is my code:
var arr = [
{"value":"abc"},
{"type":"def"},
{"status":"ghi"},
{"value":"abc"}
]
var obj={};
var key1 = "type", value="xyz";
obj[key1] = value;
var newarr = arr.filter(function(entry,i) {
if (!entry.hasOwnProperty(key1)) {
return true;
}
});
newarr.push(obj);
Please note, the obj will be dynamic so my code is working fine for first time when the property of key1 doesn't change. once I change the value of key1 from "type" to "status", It is adding objects 2 times.
Can anybody help me around this?
Try this Array.reduce() function and Object.keys() method.
array#reduce() used to recreate with new array
Object.keys() get the key of the each object .Array#map() create the array of all object keys .
Then match if not includes in the array then push with new array
Updated replace the type with new one value
var arr = [{"value":"abc"}, {"type":"def"}, {"status":"ghi"}, {"value":"xyz"}];
var key1 = "type";
var value="xyz";
var result = arr.reduce((a,b) =>{
if(!a.map(i=> Object.keys(i)[0]).includes(Object.keys(b)[0]))
{
if(b.hasOwnProperty(key1)){
b[key1]=value
}
a.push(b)
}
return a}, []);
console.log(result);
The following code should do the job:
var arr = [
{"value":"abc"},
{"type":"def"},
{"status":"ghi"},
{"value":"xyz"}
];
var obj = {};
for (i in arr) {
key = Object.keys(arr[i])[0];
obj[key] = arr[i][key];
}
console.log(obj);
The solution using ES6 Array.prototype.reduce() and Object.assign() functions:
var arr = [{"value":"abc"}, {"type":"def"}, {"status":"ghi"}, {"value":"xyz"}],
obj = arr.reduce((r,o) => Object.assign(r,o), {}),
result = Object.keys(obj).map( (k) => { o = {}; o[k]=obj[k]; return o } );
console.log(result);
You could use a hash table and filter and update all found same key objects.
var array = [{ value: "abc" }, { type: "def" }, { status: "ghi" }, { value: "ddd" }],
key = "type",
value = "xyz",
update = false,
hash = Object.create(null),
temp = {};
temp[key] = value;
array.push(temp);
array = array.filter(function (o) {
var key = Object.keys(o)[0];
if (!hash[key]) {
hash[key] = o;
return true;
}
hash[key][key] = o[key];
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
My two arrays are:
const values = ['Master Clean', '45', '650']
const names = ['servicemenus.$.name', 'servicemenus.$.duration', 'servicemenus.$.cost']
The result should be like this:
{ 'servicemenus.$.name':'Master Clean', 'servicemenus.$.duration': '45', 'servicemenus.$.cost': 650}
Since I think that you know these two Arrays needs to be the same length at all time. This for loop could help you:
const values = ['Master Clean', '45', '650']
const names = ['servicemenus.$.name', 'servicemenus.$.duration', 'servicemenus.$.cost']
var obj = {}
for (var i = 0; i < names.length; i++) {
//or check with: if (values.length > i) { assignment }
obj[names[i]] = values[i];
}
console.log(obj);
Output will be this:
Object { servicemenus.$.name: "Master Clean", servicemenus.$.duration: "45", servicemenus.$.cost: "650" }
For completion, I found this Question could help you too: Merge two arrays into one Json object
You can work with the index of the array in a forEach to refer to the other and dynamically build the object keys:
const values = ['Master Clean', '45', '650']
const names = ['servicemenus.$.name', 'servicemenus.$.duration', 'servicemenus.$.cost']
let update = { };
names.forEach( (name,idx) => {
update[name] = values[idx];
});
And that gives you the result
From the assumption that the two arrays are always equal length, we can use one of them as the basis for a loop where we build the object:
let resultingObject = {};
names.forEach((name, i) => {
resultingObject[name] = values[i];
});
console.log(resultingObject);
You can reduce an array to a single value (object in your case). Reduce function accepts accumulator, current value and index which you can use to reference a value in the second array. Object.assign constructs an object with your keys/values.
const values = ['Master Clean', '45', '650'];
const names = ['servicemenus.$.name', 'servicemenus.$.duration', 'servicemenus.$.cost'];
const res = names.reduce((acc, cur, i) => Object.assign(acc, {[cur]: values[i]}), {});
console.log(res)
And with for in,loop through the object properties and assign it new object
var newobj = {};
for( var i in names){
newobj[names[i]] = values[i];
}
console.log(newobj);
I have below two arrays:
array1 = [{
"type":"test",
"name":"name1"},
{
"type":"dev",
"name":"name2"}]
array2=[{
"type":"test",
"name":"name3"},
{
"type":"dev",
"name":"name4"},
{
"type":"prod",
"name":"name5"}]
I want to group two arrays with "type" and create a new array something like this:
finalArray=[{
"type":"test",
"info":[{
"type":"test",
"name":"name1"}],
[{
"type":"test",
"name":"name3"
}]},
{
"type":"dev",
"info":[{
"type":"dev",
"name":"name2"}],
[{
"type":"dev",
"name":"name4"}]},
{
"type":"prod",
"info":[],
[{
"type":"prod",
"name":"name5"}]
}]
Is there anyway that I can achieve this using javascript, angularjs2, lodash, jquery. I am able to group and create new object as mentioned in using lodash .groupBy. how to add your own keys for grouped output?
But only thing is always I want to push the data from second array in index=1 of "info" and first one to index=0. If any of the array does not have a "type" then the "info" array should have empty/null values.
use _.mapValues to iterate object values with key accessing
var res = _.chain(array1)
.concat(array2)
.groupBy('type')
.mapValues(function(val, key) {
return {
type: key,
info: val
};
})
.values()
.value();
It's possible to achieve the result you want in javascript, or using helper like lodash.
The last part of your question is hard to understand. If an array doesn't have "type", how would you group them. Please provide clearer explanation or modify your expected input and output.
[Updated]
Thanks for your explanation. This is the solution using plain javascript.
// get uniques type from two arrays
const uniqueTypes = new Set(array1
.concat(array2)
.map(x => x.type));
// loop the types, find item in both array
// group it
let result = Array.from(uniqueTypes).reduce((acc, curr) => {
const item1 = array1.find(x => x.type === curr);
const item2 = array2.find(x => x.type === curr);
const info1 = item1 ? [item1] : [];
const info2 = item2 ? [item2] : [];
acc = acc.concat({ type: curr, info: [info1, info2] });
return acc;
}, []);
console.log(result);
jsbin here: https://jsbin.com/mobezogaso/edit?js,console
Here's a working solution :). Hope it helps!
var array1 = [
{
"type":"test",
"name":"name1"
},
{
"type":"dev",
"name":"name2"
}
]
var array2 = [
{
"type":"test",
"name":"name3"
},
{
"type":"dev",
"name":"name4"
},
{
"type":"prod",
"name":"name5"
}
]
var newArray = array1.concat(array2);
var arr1 = [];
var arr2 = [];
var arr3 = [];
var arrTypes = [];
var finalArray = [];
var someArray = [];
for(var i in newArray)
{
if (arrTypes.indexOf(newArray[i].type) === -1){
arrTypes.push(newArray[i].type);
}
if(newArray[i].type === "test"){
arr1.push(newArray[i]);
}
else if(newArray[i].type === "dev"){
arr2.push(newArray[i]);
}
else if(newArray[i].type === "prod"){
arr3.push(newArray[i]);
}
}
someArray.push(arr1);
someArray.push(arr2);
someArray.push(arr3);
for(var j = 0; j < someArray.length; j++){
finalArray.push({
"type": arrTypes[j],
"info": someArray[j]
});
}
console.log(finalArray);
And a short (unreadable?) ES6 solution:
Concat the arrays
Reduce the array into a Map object, with the type as the key
Get the entries iterator - key (type) - value (array of objects)
Use spread to convert the entry iterator to an array
Array#Map the array of entries to the type/info objects
const array1 = [{"type":"test","name":"name1"},{"type":"dev","name":"name2"}];
const array2=[{"type":"test","name":"name3"},{"type":"dev","name":"name4"},{"type":"prod","name":"name5"}];
const result = [...array1.concat(array2).reduce((r, o) => {
r.has(o.type) ? r.get(o.type).push(o) : r.set(o.type, [o]);
return r;
}, new Map).entries()]
.map(([type, info]) => ({
type, info
}));
console.log(result);
I have one array like this one:
array1=[{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}]
I have a second array of integer :
array2=[1,3]
I would like to obtain this array without a loop for :
arrayResult = ['value1', 'value3']
Does someone know how to do it with javascript ?
Thanks in advance
Map the elements in array2 to the label property of the element in array1 with the corresponding value:
array2 // Take array2 and
.map( // map
function(n) { // each element n in it to
return array1 // the result of taking array1
.find( // and finding
function(e) { // elements
return // for which
e.value // the value property
=== // is the same as
n; // the element from array2
}
)
.label // and taking the label property of that elt
;
}
)
;
Without comments, and in ES6:
array.map(n => array1.find(e => e.value === n).label);
You can use .filter and .map, like this
var array1 = [
{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}
];
var array2 = [1, 3];
var arrayResult = array1.filter(function (el) {
return array2.indexOf(el.value) >= 0;
}).map(function (el) {
return el.label;
});
console.log(arrayResult);
A simple for-loop should suffice for this. In the future you should seriously post some code to show what you have tried.
var array1=[{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}];
var array2=[1,3];
var result = [];
for (var i = 0; i < array2.length; i++){
result.push(array1[array2[i]-1].label);
}
console.log(result); //["value1", "value3"]
JSBIN
Good answers all. If I may suggest one more alternative using Map as this seems to be suited to a key:value pair solution.
var arr1 = [ {value:1, label:'value1'}, {value:2, label:'value2'}, {value:3, label:'value3'} ];
var arr2 = [1, 3];
// create a Map of the first array making value the key.
var map = new Map( arr1.map ( a => [a.value, a.label] ) );
// map second array with the values of the matching keys
var result = arr2.map( n => map.get ( n ) );
Of course this supposes that the key:value structure of the first array will not become more complex, and could be written in the simpler form of.
var arr1 = [[1,'value1'], [2,'value2'], [3,'value3']]; // no need for names
var arr2 = [1, 3];
var map = new Map( arr1 ); // no need to arr1.map ;
var result = arr2.map( n => map.get ( n ) );
Just index the first array using the _.indexBy function:
var indexedArray1 = _.indexBy(array1, "value");
_.map(array2, function(x) { return indexedArray1[x].label; });