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
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)
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);
I have the following data :
[
{"date":1900,"data":[
{"name":"Blackbird","value":0},
{"name":"Seagull","value":1},
{"name":"Sparrow","value":0}
]},
{"date":1910,"data":[
{"name":"Owl","value":1}
]},
{"date":1920,"data":[
{"name":"Eagle","value":0},
{"name":"Albatross","value":2}
]}
]
I need to make an incremental array of arrays from it. It should look something like this :
[
[
{"name":"Blackbird","value":0,"date":1900},
{"name":"Seagull","value":1,"date":1900},
{"name":"Sparrow","value":0,"date":1900}
],
[
{"name":"Blackbird","value":0,"date":1910},
{"name":"Seagull","value":1,"date":1910},
{"name":"Sparrow","value":0,"date":1910},
{"name":"Owl","value":1,"date":1910}
],
[
{"name":"Blackbird","value":0,"date":1920},
{"name":"Seagull","value":1,"date":1920},
{"name":"Sparrow","value":0,"date":1920},
{"name":"Owl","value":1,"date":1920},
{"name":"Eagle","value":0,"date":1920},
{"name":"Albatross","value":2,"date":1920}
]
]
No matter what I have tried, I always end up with all the dates I add to the objects being equal to the last value (1920 here). I understand that the objects are copied by reference only. I have tried using array.map() (like in the answer given here, but my question was not formulated right), but I still get the same problem.
EDIT
Here's one example of code I've tried :
var temp = [];
var b = data.map(function(c, index, main) {
var year = c.date;
temp = [];
main.slice(0, index + 1).map(function(d){
var t = d.data.map(function(e){
e.date = year;
return e;
});
temp = temp.concat(t);
});
return temp;
});
console.log(b);
Here's a working example:
You need to clone the object in order to "break" the reference.
var data = [
{
"date":1900,
"data":[
{"name":"Blackbird","value":0},
{"name":"Seagull","value":1},
{"name":"Sparrow","value":0}
]
},
{
"date":1910,
"data":[
{"name":"Owl","value":1}
]
},
{
"date":1920,
"data":[
{"name":"Eagle","value":0},
{"name":"Albatross","value":2}
]
}
];
var incremental = [];
var dataHistory = null;
for(i = 0; i < data.length; i++){
var temp = dataHistory ? dataHistory.slice() : []; //.slice to clone array
//Replace all values with current date.
for(var j = 0; j < temp.length; j++){
temp[j] = JSON.parse(JSON.stringify(temp[j])); //Clone object
temp[j].date = data[i].date;
}
//Add current date to object.
for(var j = 0; j < data[i].data.length; j++){
var aux = {
name: data[i].data[j].name,
value: data[i].data[j].value,
date: data[i].date
};
temp.push(aux);
}
dataHistory = temp;
incremental.push(temp);
}
document.body.innerHTML = '<pre>' + JSON.stringify(incremental, null, 4) + '</pre>';
If you're using jQuery you can replace:
temp[j] = JSON.parse(JSON.stringify(temp[j]));
With:
temp[j] = $.extend({}, temp[j]);
Try this one:
var data = [
{"date":1900,"data":[
{"name":"Blackbird","value":0},
{"name":"Seagull","value":1},
{"name":"Sparrow","value":0}
]},
{"date":1910,"data":[
{"name":"Owl","value":1}
]},
{"date":1920,"data":[
{"name":"Eagle","value":0},
{"name":"Albatross","value":2}
]}
];
var result = data.map(function(item) {
var replacement = [];
for (var key in item.data) {
var subItem = item.data[key];
subItem.date = item.date;
replacement.push(subItem);
}
return replacement;
});
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 3) + '</pre>';
Use map, iterate over the inner array, and set the date property to each object etc.
var data = [
{"date":1900,"data":[
{"name":"Blackbird","value":0},
{"name":"Seagull","value":1},
{"name":"Sparrow","value":0}
]},
{"date":1910,"data":[
{"name":"Owl","value":1}
]},
{"date":1920,"data":[
{"name":"Eagle","value":0},
{"name":"Albatross","value":2}
]}
]
data = data.map(function(obj, i, arr) {
var o = [];
arr.slice(0, i).forEach(function(item) {
item.data.forEach(function(data) {
o.push(Object.assign({}, data))
});
});
return o.concat(obj.data.map(function(item) { item.date = obj.date; return item }));
});
document.body.innerHTML = '<pre>' + JSON.stringify(data, null, 4) + '</pre>';
Object.assign with polyfill
I have an array:
["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"]
The array can have different sets of cars, and I want to turn it into something like this:
[{
car1: ["car1-coupe"]
},{
car2: ["car2-convertible", "car2-hatchback", "car2-estate"]
},{
car3: ["car3-hatchback", "car3-estate"]
}]
How can I do this in JavaScript or Underscore?
So, assuming an array like this:
var a = ["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"];
You can do this:
var b = a.reduce(function(prev, curr){
var car = curr.split('-')[0]; // "get" the current car
prev[car] = prev[car] || []; // Initialize the array for the current car, if necessary.
prev[car].push(curr); // Add the current item to the array.
return prev;
}, {});
This will return the following object:
{
car1: ["car1-coupe"],
car2: ["car2-convertible", "car2-hatchback", "car2-estate"],
car3: ["car3-hatchback", "car3-estate"]
}
var array = ["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"];
var result = {};
for (var i = 0; i < array.length; i++) {
var key = array[i].split('-')[0]; // The car we're interested in
if (result[key]) { // Check if this car has already been initialized
result[key].push(array[i]); //add this model to the list
} else {
result[key] = [array[i]]; // initialize the array with the first value
}
}
console.log(result);
/*will return :
{
car1: ["car1-coupe"],
car2: ["car2-convertible", "car2-hatchback", "car2-estate"],
car3: ["car3-hatchback", "car3-estate"]
}
*/
var myObj = {}, myArr = [];
for( var i = 0; i < arr.length; i+=1) {
var key = arr[i].split("-")[0];
myObj = {};
myObj[key] = [];
for( var j = i; j < arr.length; j+=1 ) {
if( key === arr[j].split("-")[0])
myObj[key].push(arr[j]);
}
myArr.push(myObj);
}
I think this can be done simply with this way. One loop to get the key and another inner loop to get all values of this key.