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>
Related
I don't know what must be title for my question, I think it's so complicated. So, I have A array:
["87080207", "87101133", "91140156"]
And B Array:
["97150575", "97150575", "90141063"]
This B array, I put on html select value. Each of them(A and B array) is related. I need to show 87080207,87101133 (A array) when I choose value 97150575 (B array).
I have tried, but it didn't work.This is my code:
var a=[];
var b=[];
var arrayLength = dataComponentValuation.length;
for (var i = 0; i < arrayLength; i++) {
a.push(dataComponentValuation[i].valuated);
b.push(dataComponentValuation[i].valuator);
}
var ajoin = a.join();
var bjoin = b.join();
$('#valuatedEmpCompId_before').val(ajoin);
$('#valuator_before').val(bjoin);
In select, I put a function, this is it:
function emptyValuated() {
var valby = $("#valBy").val(); //chosen value from select
var b_valby = $("#valuator_before").val();
var b_valuated = $("#valuatedEmpCompId_before").val();
if(b_valby != ''){
if(valby != b_valby)
{
$("#valuatedEmpCompId").val('');
}
else{
$("#valuatedEmpCompId").val(b_valuated);
}
}
else{
$("#valuator_before").val(valby);
$("#valuatedEmpCompId").val(b_valuated);
}
}
Help me please...
As suggested, you could use an object as reference to the values of array A.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
object = Object.create(null);
arrayB.forEach(function (b, i) {
object[b] = object[b] || [];
object[b].push(arrayA[i]);
});
console.log(object);
I guess nowadays the Map object is a perfect solution for these jobs.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
myMap = arrayB.reduce((p,c,i) => p.has(c) ? p.set(c, p.get(c).concat(arrayA[i]))
: p.set(c,[arrayA[i]])
, new Map());
console.log(myMap.get("97150575"));
console.log(myMap.get("90141063"));
I am trying to compare the items in "item" array and the copyofOpList array to retrieve the data occurrences in copyofOpList
this is my try:
var _deleteUsedElement1 = function(item) {
for (var i = 0; i < item.length-1; i++){
for (var j = 0; j< $scope.copyofOpList.length-1; j++){
if (item[i].operationCode == $scope.copyofOpList[j].code) {
$scope.copyofOpList.splice(j, 1);
} } } };
$scope.compareArrays = function() {
...Get data from web Service
_deleteUsedElement1(item);
}
the copyofOpList array has 14 elements,and the item array has 2 array
but my code deletes only one occurrence (the first),so please how can I correct my code,to retrieve any occurances in the copyofOpList array comparing to the item array
thanks for help
I'd try to avoid looping inside a loop - that's neither a very elegant nor a very efficient way to get the result you want.
Here's something more elegant and most likely more efficient:
var item = [1,2], copyofOpList = [1,2,3,4,5,6,7];
var _deleteUsedElement1 = function(item, copyofOpList) {
return copyofOpList.filter(function(listItem) {
return item.indexOf(listItem) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [3,4,5,6,7]
}
And since I just noticed that you're comparing object properties, here's a version that filters on matching object properties:
var item = [{opCode:1},{opCode:2}],
copyofOpList = [{opCode:1},{opCode:2},{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}];
var _deleteUsedElement1 = function(item, copyofOpList) {
var iOpCodes = item.map(function (i) {return i.opCode;});
return copyofOpList.filter(function(listItem) {
return iOpCodes.indexOf(listItem.opCode) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}]
Another benefit of doing it in this manner is that you avoid modifying your arrays while you're still operating on them, a positive effect that both JonSG and Furhan S. mentioned in their answers.
Splicing will change your array. Use a temporary buffer array for new values like this:
var _deleteUsedElement1 = function(item) {
var _temp = [];
for (var i = 0; i < $scope.copyofOpList.length-1; i++){
for (var j = 0; j< item.length-1; j++){
if ($scope.copyofOpList[i].code != item[j].operationCode) {
_temp.push($scope.copyofOpList[j]);
}
}
}
$scope.copyofOpList = _temp;
};
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"]
var arr = [["test","1"],["demo","2"]];
// $.inArray() ???
// .splice() ???
// $.each() ???
$("code").html(JSON.stringify(arr));
If I will find matching array by "test" (unique) keyword , I will remove ["test","1"]
So arr after removed will be [["demo","2"]]
How can I do that ?
Playground : http://jsbin.com/ojoxuy/1/edit
This is what filter is for:
newArr = arr.filter(function(item) { return item[0] != "test" })
if you want to modify an existing array instead of creating a new one, just assign it back:
arr = arr.filter(function(item) { return item[0] != "test" })
Modificator methods like splice make code harder to read and debug.
You could do something like this:
function remove(oldArray, itemName) {
var new_array = [];
for(var i = 0, len = oldArray.length; i < len; i++) {
var arr = oldArray[i];
if (arr[0] != itemName) new_array.push(arr);
}
return new_array;
}
And call it like this:
var arr = [["test","1"],["demo","2"]];
var new_arr = remove(arr,'test');
I'm making assumptions here and not doing any real error checking but you get the idea.
Perhaps something like:
for(var i = 0; i < arr.length; i++) {
if(arr[i][0] == "test") {
arr.splice(i, 1);
break;
}
}
var arr = [["test","1"],["demo","2"]];
function checkArrayElements(a, index, arr) {
if(a[0]=="test"){
delete arr[index];
arr.splice(index,index+1);
}
}
arr.forEach(checkArrayElements);
$("code").html(JSON.stringify(arr));
NOTE: This removes any inner array in arr with the 0 element = "test"
Check this one
function rmEl(a,v)
{
for(var i=0;i<a.length;i++)
{
if(a[i][0]==v)
{
a.splice(i,i+1);
i=-1;
}
$("code").html(JSON.stringify(a));
}
return a;
}
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 } );