Here's my input
var id = '1,2,3';
var name = 'a,b,c';
var value = 'x,y,z';
How can i construct a array like this
[
{
"id" : "1",
"name" : "a",
"value" : "x",
}
,
{
"id" : "2",
"name" : "b",
"value" : "y",
}
,
{
"id" : "3",
"name" : "c",
"value" : "z",
}
]
I tried like this
var newArray = [];
newArray.push({'id':id,'name':name,'value':value })
But it gives, a single array with comma seperated value.
How can i do this Pls help
Note : I prefer only javascript
You could iterate the given strings, split them and assign the values to an object in an array.
var id = '1,2,3',
name = 'a,b,c',
value = 'x,y,z',
keys = ['id', 'name', 'value'],
result = [];
[id, name, value].forEach(function (a, i) {
a.split(',').forEach(function (b, j) {
result[j] = result[j] || {};
result[j][keys[i]] = b;
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use:
var id_split = id.split(',');
var name_split = name.split(',');
var value_split = value.split(',');
var newArray = [];
for(var i = 0; i < id_split.length; i++){
newArray.push({'id':id_split[i],'name':name_split[i],'value':value_split[i] })
}
This of course only works if the arrays are all the same length
If you know the elements length beforehand
var allIDs= '1,2,3';
var allNames= 'a,b,c';
var allValues= 'x,y,z';
var tmpArray = [];
for(var i=0;i<3;i++)
tmpArray.push(new {id: allIDs.split(',')[i] , name: allNames.split(',')[i], value: allValues.split(',')[i] });
But for a more generic solution, assuming that your comma sepparated string will always match in length
var allIDs= '1,2,3';
var allNames= 'a,b,c';
var allValues= 'x,y,z';
var tmpArray = [];
allIDs = allIDs.split(',');
allNames =allNames.split(',');
allValues = allValues.split(',');
for(var i=0;i<3;i++)
tmpArray.push(new {id: allIDs[i] , name: allNames[i], value: allValues[i] });
I would do as follows;
var id = '1,2,3'.split(","),
name = 'a,b,c'.split(","),
value = 'x,y,z'.split(","),
result = id.map((e,i) => ({id: e, name: name[i], value: value[i]}));
console.log(result);
var id = '1,2,3';
var name = 'a,b,c';
var value = 'x,y,z';
$('.resultsDiv').html(JSON.stringify(yourFun()))
function yourFun() {
ida = id.split(',');
namea = name.split(',');
valuea = value.split(',');
var returnvar = [];
for (var i = 0; i < ida.length; i++) {
returnvar.push({
"id": ida[i],
"name": namea[i],
"value": valuea[i]
});
}
return returnvar;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="resultsDiv"></div>
First, just split the lists into arrays, then you can perform a loop or use something like map/reduce to generate the compiled array.
var id = '1,2,3';
var name = 'a,b,c';
var value = 'x,y,z';
var idArray = id.split(',');
var nameArray = name.split(',');
var valueArray = value.split(',');
var newArray = idArray.map((id,i) =>
({ id: id, name: nameArray[i], value: valueArray[i] })
);
console.log(newArray);
Related
var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"}];
var array2 =[ {"name":"SAM","surname":"SAMEERA"}];
I want output to be like this:
[{"name":"SAM","surname":"SAMEERA","location":"mumbai","age":"22"}];
using javascript and underscorejs
My attempt is as below:
var workingValues = _.filter(array1, function(item){ return item});
console.log(workingValues);
var validItems = [];
for(var i =0 ; i < array2.length; i++){
var item = array2[i];
console.log(item);
var findItems = _.filter(array1,function(ite) {
return ite.name.toUpperCase() == item.name.toUpperCase() && ite.surname.toUpperCase() == item.surname.toUpperCase()});
validItems.push(item);
console.log(findItems);
}
var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"}];
var array2 =[ {"name":"SAM","surname":"SAMEERA"}];
var result = [{...array1[0],...array2[0]}];
console.log(result);
You can try this
var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"},{"name":"sam123","surname":"sameera123","location":"mumbai","age":"22"} ];
var array2 =[ {"name":"SAM","surname":"SAMEERA"},{"name":"SAM123","surname":"SAMEERA123"}];
var ret = [];
for(var i = 0; i < array1.length; i += 1) {
var newArray = array2.filter(function (el) {
return el.name.toUpperCase() == array1[i].name.toUpperCase() && el.surname.toUpperCase() ==array1[i].surname.toUpperCase();
});
if(newArray.length ==0)
{
ret.push(array1[i]);
}
else
{
array1[i].name = newArray[0].name; //change valuse
array1[i].surname = newArray[0].surname; //change valuse
ret.push(array1[i]);
}
};
console.log(ret);
Based on the limited data you've provided.
var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"}];
var array2 =[ {"name":"SAM","surname":"sameera"}];
console.log( _.extend(array2, array1))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
var array1 = [{
"name":"sam",
"surname":"sameera",
"location":"mumbai",
"age":"22"
}];
var array2 =[{
"name":"SAM",
"surname":"sameera"
}];
var mergearray= array1 .concat(array2);
I am trying to convert an array(with email addresses) in to object.
How to insert values in value array for one key?
var list = [
"john#yahoo.com", "rami#gmail.com",
"josh#yahoo.com", "bale#gmail.com"
];
(function() {
var obj1 = {};
for (var a = 0, b = list.length; b > a; a++) {
var str = list[a].split("#");
var arr = [];
arr.push(str[0]);
if (!(str[1] in obj1)) {
obj1[str[1]] = []; //arr.push(str[0])];
}
Object.values(obj1[str[1]]).push(str[0])
};
console.log(obj1);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
expected output
{
"gmail.com" : ["a","b","c"],
"yahoo.com" : ["de","e","f"]
}
I also want to add like
{
"gmail.com" : [3],//1+1+1
"yahoo.com" : [4]//1+1+1+1
}
var list = [
"john#yahoo.com", "rami#gmail.com",
"josh#yahoo.com", "bale#gmail.com"
];
obj = {};
list.map(x => x.split('#')[1]).forEach(x => obj[x] = [])
list.forEach(email => obj[email.split('#')[1]].push(email))
console.log(obj)
/*
{
"yahoo.com": [
"john#yahoo.com",
"josh#yahoo.com"
],
"gmail.com": [
"rami#gmail.com",
"bale#gmail.com"
]
}
*/
Explanation:
Created a blank object obj. Then I iterated on list and retrieved all the domains by list.map(x => x.split('#')[1]).
With domains in hand, I setup-ed the object to have the structure { 'yahoo.com': [], 'gmail.com': [] }
Then I iterated on list again and added the email if domain contained the corresponding part, giving resultant object.
Edit:
It can also be done in single iteration this way:
var list = [
"john#yahoo.com", "rami#gmail.com",
"josh#yahoo.com", "bale#gmail.com"
]
obj = {}
list.forEach(email => {
let domain = email.split('#')[1]
if (!obj[domain]) obj[domain] = []
if (obj[domain].indexOf(email) < 0) obj[domain].push(email)
})
console.log(obj)
Here, I'm iterating on list, extracting the domain, setting up the key with [] if it doens't exist and then pushing the email into that. It also makes sure that no duplicate emails are pushed.
You can simply push the values in the array if the key is found in object otherwise add the array
var list = [
"john#yahoo.com", "rami#gmail.com",
"josh#yahoo.com", "bale#gmail.com"
];
(function() {
var obj1 = {};
for (var a = 0; a < list.length; a++) {
var str = list[a].split("#");
if(obj1[str[1]]) {
obj1[str[1]].push(list[a])
} else {
obj1[str[1]] = [list[a]]; //arr.push(str[0])];
}
};
console.log(obj1);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your code is almost correct, there is just a minor bug, change your line:
Object.values(obj1[str[1]]).push(str[0])
To
obj1[str[1]].push(list[a]);
And it works fine.
var list = [
"john#yahoo.com", "rami#gmail.com",
"josh#yahoo.com", "bale#gmail.com"
];
(function() {
var obj1 = {};
for (var a = 0, b = list.length; b > a; a++) {
var str = list[a].split("#");
var arr = [];
arr.push(str[0]);
if (!(str[1] in obj1)) {
obj1[str[1]] = []; //arr.push(str[0])];
}
obj1[str[1]].push(list[a]);
};
console.log(obj1);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Array.prototype.reduce is typically used to translate array data to object form.
See below for a practical example 👇
// Emails.
const emailAddresses = ["bale#gmail.com", "john#yahoo.com", "rami#gmail.com","josh#yahoo.com"]
// Group By Domain.
const groupByDomain = addresses => addresses.reduce((acc, email) => {
const [prefix, domain] = email.split(/#/)
const exists = acc[domain]
if (exists) acc[domain].push(email)
else acc[domain] = [email]
return acc
}, {})
// Output.
const output = groupByDomain(emailAddresses)
// Proof.
console.log(output)
I have the following js array:
for(var j = 0; j < array.length; j++){
arr.push([array[j][0],array[j][1],array[j][2]]);
}
And it translates into this:
Number, type, qty
[[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]]
What I've been trying to do is to filter the unique product number array[j][0] and sum the qty array[j][2] if there's more than one and I was able to do the unique filter by doing the following:
for(var o = 0; o < arr.length; o++){
if (!n[arr[o][1]]){
n[arr[o][1]] = true
r.push(arr[o]);
}
}
I would like your help to figure this out.. What I'm expecting to achieve is something like this:
[[12345, "product", "25"],[1234567, "other", "10"]]
Since product 12345 was repeated I only need to display it once and sum the qty of the other products with the same product number.
var productIndex = {};
var result = [];
for (var i = 0; i < arr.length; i++) {
var productId = arr[i][0];
if (productIndex[productId] === undefined) {
productIndex[productId] = result.length;
result.push(arr[i]);
} else {
var index = productIndex[productId];
result[index][2] = String(+result[index][2] + +arr[i][2]);
}
}
I am sure there are better ways. But I just changed it to an object, added them and changed it back to an array. Here you go:
https://jsfiddle.net/ct6to1Lv/
var a = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];
var b = {};
var c = [];
for(var i = 0; i < a.length; i++) {
if(!b.hasOwnProperty(a[i][0])) {
b[a[i][0]] = {};
b[a[i][0]]['qty'] = 0;
}
b[a[i][0]]['id'] = a[i][0];
b[a[i][0]]['name'] = a[i][1];
b[a[i][0]]['qty'] += parseInt(a[i][2]);
}
for(key in b) {
c[c.length] = [b[key]['id'], b[key]['name'], b[key]['qty']];
}
$(function(){
$('#console').append(a.toString()+'<br />');
$('#console').append(JSON.stringify(b)+'<br />');
$('#console').append(c.toString());
});
var arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];
var obj = {};
arr.forEach(function(e){
var t = e[0];
if(obj[t]) {
obj[t][2] += +e[2];
} else {
t = [];
t[0] = e[0];
t[1] = e[1];
t[2] = +e[2];
obj[e[0]] = t;
}
});
var res = [];
Object.keys(obj).forEach(function(k) {
res.push(obj[k]);
});
console.log(res);
Result:
[ [ 12345, 'product', 25 ], [ 1234567, 'other', 10 ] ]
To complete the possibillities, here a solution with a temporary object, which is hidden in this.
var data = [[12345, "product", "10"], [12345, "product", "15"], [1234567, "other", "10"]],
result = function (data) {
var r = [];
data.forEach(function (a) {
if (!this[a[0]]) {
this[a[0]] = [a[0], a[1], 0];
r.push(this[a[0]]);
}
this[a[0]][2] += +a[2];
}, {});
return r;
}(data);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
See Array.prototype.reduce() and Array.prototype.sort()
var list = [[12345, "product", "10"], [12345, "product", "15"], [1234567, "other", "10"], [12345, "product", "5"]];
//first we sort the array by id
//#pv = previous value; #cv = current value
list.sort(function(pv, cv) {
var a = +pv[0],
b = +cv[0];
return a - b;
});
//reduce the array for repeated elements
//#pv = previous value; #cv = current value
var reduced = list.reduce(function (pv, cv) {
//slice keeps reference when element is an object/array
var last = pv.slice(-1)[0];
if (last === undefined) return [cv];
//compares the id
if (last[0] == cv[0])
last[2] = +last[2] + (+cv[2]); //sums values
else pv.push(cv); //order elements
return pv;
}, []); //[] initial value for #pv
console.log(reduced);
I have this code: (it reads a folder of mp3 files and retrieves all paths)
var base = "../media/audio/";
var arr1 = [
{path:"../media/audio/Numbers/Cat1/01.mp3"},
{path:"../media/audio/Numbers/Cat1/02.mp3"},
{path:"../media/audio/Numbers/Cat1/03.mp3"},
{path:"../media/audio/Numbers/Cat1/04.mp3"},
{path:"../media/audio/Letters/Cat1/01.mp3"},
{path:"../media/audio/Letters/Cat1/02.mp3"},
{path:"../media/audio/Letters/Cat1/03.mp3"},
{path:"../media/audio/Color/Cat1/01.mp3"},
{path:"../media/audio/Color/Cat1/02.mp3"},
{path:"../media/audio/Color/Cat1/03.mp3"}
];
I want to get this:
var arr2 = [
[{
category:"Numbers",
path:[
{path:"../media/audio/Numbers/Cat1/01.mp3"},
{path:"../media/audio/Numbers/Cat1/02.mp3"},
{path:"../media/audio/Numbers/Cat1/03.mp3"},
{path:"../media/audio/Numbers/Cat1/04.mp3"}
]
}],
[{
category:"Letters",
path:[
{path:"../media/audio/Letters/Cat1/01.mp3"},
{path:"../media/audio/Letters/Cat1/02.mp3"},
{path:"../media/audio/Letters/Cat1/03.mp3"}
]
}],
[{
category:"Color",
path:[
{path:"../media/audio/Color/Cat1/01.mp3"},
{path:"../media/audio/Color/Cat1/02.mp3"},
{path:"../media/audio/Color/Cat1/03.mp3"}
]
}]
];
Find every category after the 'base' string, split them in array, inside each array and object with category and path property.
Here you go.
var output = document.getElementById("output");
function splitSearch(base, arr1) {
var categoryList = {};
var baseLen = base.length;
// Split paths into categories
arr1.forEach(function(inPath) {
var subPath = inPath.path.substr(baseLen);
var category = subPath.split("/")[0];
if (!categoryList.hasOwnProperty(category)) {
categoryList[category] = [];
}
categoryList[category].push(inPath);
});
// Transform categoryList into array format requested
var arr2 = [];
for (var category in categoryList) {
arr2.push({ category: category, path: categoryList[category] });
}
return arr2;
}
var base = "../media/audio/";
var arr1 = [
{path:"../media/audio/Numbers/Cat1/01.mp3"},
{path:"../media/audio/Numbers/Cat1/02.mp3"},
{path:"../media/audio/Numbers/Cat1/03.mp3"},
{path:"../media/audio/Numbers/Cat1/04.mp3"},
{path:"../media/audio/Letters/Cat1/01.mp3"},
{path:"../media/audio/Letters/Cat1/02.mp3"},
{path:"../media/audio/Letters/Cat1/03.mp3"},
{path:"../media/audio/Color/Cat1/01.mp3"},
{path:"../media/audio/Color/Cat1/02.mp3"},
{path:"../media/audio/Color/Cat1/03.mp3"}
];
var result = splitSearch(base, arr1);
output.innerHTML += JSON.stringify(result);
<div id="output" />
This is what you are looking for:
var arr1 = [
{path:"../media/audio/Numbers/Cat1/01.mp3"},
{path:"../media/audio/Numbers/Cat1/02.mp3"},
{path:"../media/audio/Numbers/Cat1/03.mp3"},
{path:"../media/audio/Numbers/Cat1/04.mp3"},
{path:"../media/audio/Letters/Cat1/01.mp3"},
{path:"../media/audio/Letters/Cat1/02.mp3"},
{path:"../media/audio/Letters/Cat1/03.mp3"},
{path:"../media/audio/Color/Cat1/01.mp3"},
{path:"../media/audio/Color/Cat1/02.mp3"},
{path:"../media/audio/Color/Cat1/03.mp3"}
];
var basePath = "\.\.\/media\/audio\/";
var regex = new RegExp('^' + basePath + '(.*?)\/');
var categories = {}, arr2 = [];
for (var i=0, x=arr1.length; i < x; i++) {
var category = arr1[i].path.match(regex)[1];
if (!categories[category]) {
arr2.push({
category : category,
path : []
});
categories[category] = true;
}
for (var ii=0, l = arr2.length; ii < l; ii++) {
if (arr2[ii].category == category) {
arr2[ii].path.push(arr1[i]);
break;
}
}
}
Could probably be cleaned up a bit but should get you where you need to go
I want to print the minimum variable 'name' in JS. Currently it prints the minimaum value. I rather want the variable name. For eg:- In the current code, it gives me 4, but I want c. How can I do this?
<script>
function myFunction()
{
var a = 5;
var b =10;
var c = 4;
document.getElementById("demo").innerHTML=Math.min(a,b,c);
}
</script>
Working DEMO
This should do the trick:
//Push values to object
var age = {};
age.a = 5;
age.b = 10;
age.c = 4;
var min = Infinity, name;
// Loop through object to get min value and then find relevant name
for(var x in age) {
if( age[x] < min) {
min = age[x];
name = x;
}
}
console.log ( 'property name is ' + name + ' and value is ' + min );
You could put your values in an array like
var values = [
{ name: 'a', value: 5 },
{ name: 'b', value: 10 },
{ name: 'c', value: 4 }
];
and then use the filter method with the hint from Ahmad's comment:
var min_value = Math.min.apply(null, values.map(function(item) {
return item.value;
}));
var min_name = values.filter(function (item) {
return item.value == min_value;
})[0].name;
See this fiddle for a working example.
Store the values in an array of objects. Each object will contain a name and value property. Then just iterate through the values and store the lowest.
var values = [
{
"name": "a",
"value": 5
},
{"name":"b",
"value":10
},
{
"name":"c",
"value":4
}
];
function min(arr){
var minValue = {};
for(var x = 0; x < arr.length; x++){
if(arr[x].value < minValue.value || !minValue.value){
minValue = arr[x];
}
}
return minValue.name;
};
document.getElementById("demo").innerHTML = min(values);
JS Fiddle: http://jsfiddle.net/AgMbW/
You can do this way:
var obj = {"names":["a","b","c"], "values":[5,10,4]}
var min = Math.min.apply( Math, obj["values"] );
var result = obj["names"][obj["values"].indexOf(min)];
document.getElementById("demo").innerHTML=result;
Here the fiddle: http://jsfiddle.net/eUcug/
Way 1 :
var x = 5;var getName = function(value){if(value === 5) return 'x'; else return null}
Way 2 :
NameValue.getName = function(value){for(i = 1;i<=2;i++){if(this["val" + i].value === value) {return this["val" + i].name;break;}console.log(this["val" + i]);}return null;}NameValue.val2 = {name : 'y',value : 1};NameValue.prototype.add({name : 'x',value : 10})
NameValue.getName(10); //return "x"
I hope you can understand how to find the variable name.