I have the following array:
var fruits = ["orange","orange,apple","apple,orange,pear"];
I am trying to achieve the following:
fruits = ["orange","apple","pear"]
Any suggestions, thanks!
Here's one way to do it:
fruits = fruits.reduce(function (p, c) {
return p.concat(c.split(","));
}, []).filter(function(e, i, a) {
return a.indexOf(e) === i;
});
(EDIT: Note that .filter() and .reduce() are not supported in IE8 or older, but there are shims available if you need to support older IE.)
There is no readymade way to achieve this.
What you could do is use associative arrays that act like dictionaries. Iterate through the list, read each element, split it and store it in an associative array with the key as the fruit name, and the value as the fruit name too. Something like:
fruits["orange"] = "orange";
If the value already exists in fruits[], it will simply be overwritten. At the end, you'll have as many keys in fruits[] as there are unique fruits.
EDIT:
var fruits = ["orange", "orange,apple", "apple,orange,pear"];
var a = fruits.toString().split(",");
var obj = new Object();
for (var i = 0; i < a.length; i++) {
obj[a[i]] = a[i];
}
for (var key in obj) {
alert(key);
}
Will give you the expected result.
var fruits = ["orange","orange,apple","apple,orange,pear"];
var uniqueVal = [];
$.each(fruits, function(i, el){
var splitVals = el.split(',');
for(var i=0; i<splitVals.length; i++ ){
if($.inArray(splitVals[i], uniqueVal) === -1) uniqueVal.push(splitVals[i]);
}
});
This should work:
var fruits = ["orange","orange,apple","apple,orange,pear"];
var out = [];
$(fruits).each(function(i) {
var s = fruits[i].split(',');
$(s).each(function(i) {
if($.inArray(s[i], out)===-1)
{
out.push(s[i]);
}
});
});
JSFIddle: http://jsfiddle.net/rRC65/
This uses an object to capture the elements, then return its keys. And no need for shims.
function remdupes(arr) {
var obj = {}, out = [];
for (var i = 0, l = arr.length; i < l; i++) {
var el = arr[i].split(',');
for (var ii = 0, ll = el.length; ii < ll; ii++) {
obj[el[i]] = true;
}
}
for (var key in obj) { out.push(key); }
return out;
}
Note that the last couple of lines:
for (var key in obj) { out.push(key); };
return out
can be rewritten:
return Object.keys(obj);
try this
var fruits = ["orange","orange,apple","apple,orange,pear"];
if you want to split the 2nd elements and concat the strings
fruits.concat(fruits[1].split(","))
or you want all the elements split and concat then uniq
var new_fruits = [];
$.each(fruits, function(i, el){
fruits.concat(fruits[i].split(","))
if($.inArray(el, new_fruits) === -1) new_fruits.push(el);
});
or using underscore.js
_.uniq(fruits, false)
You could do this like so (eliminateDuplicates) :
fruits = fruits.join(','); // "orange,orange,apple,apple,orange,pear"
fruits = fruits.split(','); // ["orange", "orange", "apple", "apple", "orange", "pear"]
fruits = eliminateDuplicates(fruits); // ["orange", "apple", "pear"]
Related
I'm trying to access elements from a JavaScript array:
[["1","John"],["2","Rajan"],["3","Hitesh"],["4","Vin"],["5","ritwik"],["6","sherry"]]
I want to access
1, 2, 3, 4, 5, 6 separately in a variable and John, Rajan, Hitesh, Vin, Ritwik, Sherry separately in a variable.
I tried converting it to a string and split(), but it doesn't work.
this is code i tried
var jArray = <?php echo json_encode($newarray); ?> ;
var nJarr = jArray[0]; nJarr.toString();
var res = nJarr.split(","); var apname = res[0];
alert(apname);
but there's no alert appearing on the screen
If you are open to using Underscore, then it's just
var transposed = _.zip.apply(0, arr);
and the arrays you are looking for will be in transposed[0] and transposed[1].
You can write your own transpose function fairly easily, and it's more compact if you can use ES6 syntax:
transpose = arr => Object.keys(arr[0]).map(i => arr.map(e => e[i]));
>> transpose([["1","John"], ["2","Rajan"], ...]]
<< [[1, 2, ...], ["John", "Rajan", ...]]
If you want an ES5 version, here's one with comments:
function transpose(arr) { // to transpose an array of arrays
return Object.keys(arr[0]) . // get the keys of first sub-array
map(function(i) { // and for each of these keys
arr . // go through the array
map(function(e) { // and from each sub-array
return e[i]; // grab the element with that key
})
))
;
}
If you prefer old-style JS:
function transpose(arr) {
// create and initialize result
var result = [];
for (var i = 0; i < arr[0].length; i++ ) { result[i] = []; }
// loop over subarrays
for (i = 0; i < arr.length; i++) {
var subarray = arr[i];
// loop over elements of subarray and put in result
for (var j = 0; j < subarray.length; j++) {
result[j].push(subarray[j]);
}
}
return result;
}
Do it like bellow
var arr = [["1","John"],["2","Rajan"],["3","Hitesh"],["4","Vin"],["5","ritwik"],["6","sherry"]];
var numbers = arr.map(function(a){return a[0]}); //numbers contain 1,2,3,4,5
var names = arr.map(function(a){return a[1]}); //names contain John,Rajan...
Try this:
var data = [["1","John"],["2","Rajan"],["3","Hitesh"],["4","Vin"],["5","ritwik"],["6","sherry"]];
var IDs = [];
var names = [];
for(i=0; i<data.length; i++)
{
IDs.push(data[i][0]);
names.push(data[i][1]);
}
console.log(IDs);
console.log(names);
Here is the working fiddle.
i have an array like
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
How can i retrive an array with only id like?
myArrayResult = [73,45]
with jQuery or javascript.
thanks
Use map
myArrayResult = myArray.map(function (el) {
return el.id; // if you want get id as Number, just add +el.id
})
Example
You could do
var myArrayResult = myArray.map(function (item) {
return item.id;
}
Or if you don't have a true browser (ie. IE8 or less)
var myArrayResult = [];
for (var i = 0, l = myArray.length; i < l; i++) {
myArrayResult.push(myArray[i].id);
}
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
myArrayResult=[];
$.each(myArray,function(index,val){
myArrayResult.push(val.id);
});
alert(myArrayResult);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
I have two JavaScript arrays below that both have the same number of entries, but that number can vary.
[{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}]
[{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}]
I want to combine these two arrays so that I get
[{"5006":"GrooveToyota"},{"5007":"GrooveSubaru"},{"5008":"GrooveFord"}]
I'm not sure how to put it into words but hopefully someone understands. I would like to do this with two arrays of arbitrary length (both the same length though).
Any tips appreciated.
It's kind of a zip:
function zip(a, b) {
var len = Math.min(a.length, b.length),
zipped = [],
i, obj;
for (i = 0; i < len; i++) {
obj= {};
obj[a[i].branchids] = b[i].branchnames;
zipped.push(obj);
}
return zipped;
}
Example (uses console.log ie users)
var ids = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}];
var names = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}];
var combined = [];
for (var i = 0; i < ids.length; i++) {
var combinedObject = {};
combinedObject[ids[i].branchids] = names[i].branchnames;
combined.push(combinedObject);
}
combined; // [{"5006":"GrooveToyota"},{"5006":"GrooveSubaru"},{"5006":"GrooveFord"}]
Personally, I would do it IAbstractDownvoteFactor's way (+1), but for another option, I present the following for your coding pleasure:
var a = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}];
var b = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}];
var zipped = a.map(function(o,i){ var n={};n[o.branchids]=b[i].branchnames;return n;});
similar to #robert solution but using Array.prototype.map
var ids = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}],
names = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}],
merged = ids.map(function (o, i) { var obj = {}; obj[o.branchids]=names[i].branchnames; return obj; });
merged; //[{5006: "GrooveToyota"}, {5006: "GrooveSubaru"}, {5006:"GrooveFord"}]
Cheers!
Suppose I have the following object obj:
obj = {
'key1' : ['1','2','3'],
'key2' : ['1','2','9'],
'key3' : ['1','3','5']
}
How can I transform obj into two arrays that look like the following?
allOfTheKeys = ['key1','key2','key3']
allOfTheArrays = ['1','2','3','5','9']
Something like
allKeys = [];
allElems = [];
for(var k in obj){
allKeys.push(k);
for(var e in obj[k]){
allElem.push(e)
}
}
Actually, in jQuery you can do it more concisely using each() (warning, this isn't tested code):
jQuery.each(obj,function(key){
allKeys.push(key);
jQuery.each(obj[key],function(elem){
allElems.push(elem);
}
});
Okay, you don't want repeats, add in
if(!(elem in allElems)) allElems.push(elem);
As I saw, other answers return repeated values. Here you have the solution (tested):
var allOfTheKeys = [], allOfTheArrays = [], nonRepeatedElems = {};
for(var key in obj){
allOfTheKeys.push(key);
for(var i=0; i< obj[key].length; i++)
nonRepeatedElems[obj[key][i]] = true;
}
for(var e in nonRepeatedElems )
allOfTheArrays.push(e);
If someone's wondering what nonRepeatedElems is, it's a hash table for the array values, whose key is the array element value. So I don't get repeated elements.
If you want your values to be ordered, just call allOfTheArrays.sort(); in the end.
EDIT: #float, Here you have a more understandable solution:
var allOfTheKeys = [], allOfTheArrays = [];
for(var key in obj){
allOfTheKeys.push(key);
for(var i=0; i< obj[key].length; i++){
var arrayElem = obj[key][i];
if(!$.inArray(arrayElem, allOfTheArrays)) //Add to the array if it doesn't exist yet
allOfTheArrays.push(arrayElem);
}
}
I have the following JavaScript Array:
var jsonArray = { 'homes' :
[
{
"home_id":"203",
"price":"925",
"sqft":"1100",
"num_of_beds":"2",
"num_of_baths":"2.0",
},
{
"home_id":"59",
"price":"1425",
"sqft":"1900",
"num_of_beds":"4",
"num_of_baths":"2.5",
},
// ... (more homes) ...
]}
I want to convert this to the following type of Array (pseudo code):
var newArray = new Array();
newArray.push(home_id's);
How can I do that?
Notice how the newArray only has home_ids from the big jsonArray array.
Just make a new array and copy the old values in.
var ids = [];
for (var i = 0; i < jsonArray.homes.length; i++) {
ids[i] = jsonArray.homes[i].home_id;
}
Again, jsonArray is not an array but an object, but jsonArray.homes is
var arr = [];
for (var i=0, len = jsonArray.homes.length; i < len; i++){
arr.push(jsonArray.homes[i].home_id);
}
Here's one iterative way:
function getPropertyValues (array, id) {
var result = [];
for ( var hash in array ) {
result.push( array[hash][id]);
}
return result;
}
var home_ids = getPropertyValues(jsonArray.homes, "home_id");
Or if you want to do it real quick and dirty (and you are only targeting modern Javascript capable engines):
var home_ids = jsonArray.homes.map( function(record) { return record.home_id } );