I get this array in my chrome console, using this method $("#gallery_thumbnails .owl-item.active").get();:
Array[5]
0:div.owl-item.active
1:div.owl-item.active.synced
2:div.owl-item.active
3:div.owl-item.active
4:div.owl-item.active
But I want only the array indexs, like this:
How can I get this result?
Iterate over your object array and save keys to new array.
var out = [];
for (key in arrays) {
out.push(key);
}
console.log(out);
Or as suggested by other user, use this method:
var out = [];
for (var i = 0; i < array.length; i++) {
out.push(i);
}
console.log(out);
You could use the map method from jQuery
$.map($("#gallery_thumbnails .owl-item.active").get(), function (val, i) {
return i;
});
Related
I have not been able to figure out how to properly accomplish this.
I have a JS array of objects that looks like this:
[{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}]
I would like to convert this into a simple, single JS array, without any of the keys, it should look like this:
[
"09599",
"KCC",
"000027",
"Johns" ]
The IDs can be dropped entirely. Any help would be really appreciated.
Simply iterate the original array, pick the interesting keys and accumulate them in another array, like this
var keys = ['num', 'name'],
result = [];
for (var i = 0; i < data.length; i += 1) {
// Get the current object to be processed
var currentObject = data[i];
for (var j = 0; j < keys.length; j += 1) {
// Get the current key to be picked from the object
var currentKey = keys[j];
// Get the value corresponding to the key from the object and
// push it to the array
result.push(currentObject[currentKey]);
}
}
console.log(result);
// [ '09599', 'KCC', '000027', 'Johns' ]
Here, data is the original array in the question. keys is an array of keys which you like to extract from the objects.
If you want to do this purely with functional programming technique, then you can use Array.prototype.reduce, Array.prototype.concat and Array.prototype.map, like this
var keys = ['num', 'name'];
console.log(data.reduce(function (result, currentObject) {
return result.concat(keys.map(function (currentKey) {
return currentObject[currentKey];
}));
}, []));
// [ '09599', 'KCC', '000027', 'Johns' ]
You can use Object.keys() and .forEach() method to iterate through your array of object, and use .map() to build your filtered array.
var array = [{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}];
var filtered = array.map(function(elm){
var tmp = [];
//Loop over keys of object elm
Object.keys(elm).forEach(function(value){
//If key not equal to id
value !== 'id'
//Push element to temporary array
? tmp.push(elm[value])
//otherwise, do nothing
: false
});
//return our array
return tmp;
});
//Flat our filtered array
filtered = [].concat.apply([], filtered);
console.log(filtered);
//["09599", "KCC", "000027", "Johns"]
How about using map :
var data = [
{"num":"09599","name":"KCC","id":null}
{"num":"000027","name":"Johns","id":null}
];
var result = data.map(function(obj) {
return [
obj.num,
obj.name,
obj.id
];
});
Here is my functions:
map:
function () {
// initialize KEY
// initialize INDEX (0..65536)
// initialize VALUE
var arr = [];
arr[INDEX] = { val: VALUE, count: 1 };
emit(KEY, { arr: arr });
}
reduce:
function (key, values) {
var result = { arr: [] };
for (var i = 0; i < values.length; i++) {
values[i].arr.forEach(function (item, i) {
if (result.arr.hasOwnProperty(i)) {
result.arr[i].val += item.val;
result.arr[i].count += item.count ;
} else {
result.arr[i] = item;
}
});
}
As you can see, I'm trying to send associative array from map to reduce. But when I try to enumerate values of array values[i].arr.forEach I get listing 0..max_index. So, every reduce I have to enumerate a lot of undefined elements.
When I try to enumerate values of array (arr) at map I get expected result (only defined elements).
Actually, I don't sure that associative array is best solution for my task. But I can't find faster way to find element by id.
Could you please answer the questions:
Why differences of array processing at map and
reduce?
What data structure I should use (or how I should use my array) to optimize my current solution?
I decided to use object:
var arr = {};
arr[INDEX] = { val: VALUE, count: 1 };
It is works with for .. in as expected.
I'm trying to loop through childNodes like this:
var children = element.childNodes;
children.forEach(function(item){
console.log(item);
});
However, it output Uncaught TypeError: undefined is not a function due to forEach function. I also try to use children instead of childNodes but nothing changed.
Does anybody know what's going on?
The variable children is a NodeList instance and NodeLists are not true Array and therefore they do not inherit the forEach method.
Also some browsers actually support it nodeList.forEach
ES5
You can use slice from Array to convert the NodeList into a proper Array.
var array = Array.prototype.slice.call(children);
You could also simply use call to invoke forEach and pass it the NodeList as context.
[].forEach.call(children, function(child) {});
ES6
You can use the from method to convert your NodeList into an Array.
var array = Array.from(children);
Or you can also use the spread syntax ... like so
let array = [ ...children ];
A hack that can be used is NodeList.prototype.forEach = Array.prototype.forEach and you can then use forEach with any NodeList without having to convert them each time.
NodeList.prototype.forEach = Array.prototype.forEach
var children = element.childNodes;
children.forEach(function(item){
console.log(item);
});
See A comprehensive dive into NodeLists, Arrays, converting NodeLists and understanding the DOM for a good explanation and other ways to do it.
I'm very late to the party, but since element.lastChild.nextSibling === null, the following seems like the most straightforward option to me:
for(var child=element.firstChild; child!==null; child=child.nextSibling) {
console.log(child);
}
Here is how you can do it with for-in loop.
var children = element.childNodes;
for(var child in children){
console.log(children[child]);
}
const results = Array.from(myNodeList.values()).map(parser_item);
NodeList is not Array
but NodeList.values() return a Array Iterator, so can convert it to Array.
Couldn't resist to add another method, using childElementCount. It returns the number of child element nodes from a given parent, so you can loop over it.
for(var i=0, len = parent.childElementCount ; i < len; ++i){
... do something with parent.children[i]
}
Try with for loop. It gives error in forEach because it is a collection of nodes nodelist.
Or this should convert node-list to array
function toArray(obj) {
var array = [];
for (var i = 0; i < obj.length; i++) {
array[i] = obj[i];
}
return array;
}
Or you can use this
var array = Array.prototype.slice.call(obj);
Here is a functional ES6 way of iterating over a NodeList. This method uses the Array's forEach like so:
Array.prototype.forEach.call(element.childNodes, f)
Where f is the iterator function that receives a child nodes as it's first parameter and the index as the second.
If you need to iterate over NodeLists more than once you could create a small functional utility method out of this:
const forEach = f => x => Array.prototype.forEach.call(x, f);
// For example, to log all child nodes
forEach((item) => { console.log(item); })(element.childNodes)
// The functional forEach is handy as you can easily created curried functions
const logChildren = forEach((childNode) => { console.log(childNode); })
logChildren(elementA.childNodes)
logChildren(elementB.childNodes)
(You can do the same trick for map() and other Array functions.)
Try this [reverse order traversal]:
var childs = document.getElementById('parent').childNodes;
var len = childs.length;
if(len --) do {
console.log('node: ', childs[len]);
} while(len --);
OR [in order traversal]
var childs = document.getElementById('parent').childNodes;
var len = childs.length, i = -1;
if(++i < len) do {
console.log('node: ', childs[i]);
} while(++i < len);
If you do a lot of this sort of thing then it might be worth defining the function for yourself.
if (typeof NodeList.prototype.forEach == "undefined"){
NodeList.prototype.forEach = function (cb){
for (var i=0; i < this.length; i++) {
var node = this[i];
cb( node, i );
}
};
}
for (var i = 0; i < e.childNodes.length; i++) {
var id = e.childNodes[i].id;
}
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 8 years ago.
If I have an object such that
var object = function(key,text)
{
this.key = key;
this.text = text;
}
And create an array of these objects
var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');
is there a way that I can retrieve only one of the properties of all of the objects in the array? For example:
var keyArray = objArray["key"];
The above example doesn't return set keyArray to anything, but I was hoping it would be set to something like this:
keyArray = [
'key1',
'key2',
'key3']
Does anyone know of a way to do this without iterating through the objArray and manually copying each key property to the key array?
This is easily done with the Array.prototype.map() function:
var keyArray = objArray.map(function(item) { return item["key"]; });
If you are going to do this often, you could write a function that abstracts away the map:
function pluck(array, key) {
return array.map(function(item) { return item[key]; });
}
In fact, the Underscore library has a built-in function called pluck that does exactly that.
var object = function(key,text) {
this.key = key;
this.text = text;
}
var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');
var keys = objArray.map(function(o,i) {
return o.key;
});
console.log(keys); // ["key1", "key2", "key3"]
JS Bin Example
http://jsbin.com/vamey/1/edit
Note that older browsers may not support map but you can easily do this with a for loop:
var keys = [];
for (var i = 0; i < objArray.length; i++) {
keys.push(objArray[i].key);
}
JS Bin Example
http://jsbin.com/redis/1/edit
You would want to do something like this:
objArray.map(function (obj) { return obj.key; });
Here is a JSFiddle to demo: http://jsfiddle.net/Q7Cb3/
If you need older browser support, you can use your own method:
JSFiddle demo: http://jsfiddle.net/Q7Cb3/1/
function map (arr, func) {
var i = arr.length;
arr = arr.slice();
while (i--) arr[i] = func(arr[i]);
return arr;
}
Well something has to iterate through the elements of the array. You can use .map() to make it look nice:
var keys = objArray.map(function(o) { return o.key; });
You could make a function to generate a function to retrieve a particular key:
function plucker(prop) {
return function(o) {
return o[prop];
};
}
Then:
var keys = objArray.map(plucker("key"));
Really "objArray" is an array that have 3 objects inside, if you want list of keys, you can try this:
var keys = [];
for(a in objArray) {
keys.push(objArray[a].key);
}
You have in var keys, the three keys.
Hope that helps! :)
Trying to change my for loop with .map method of jquery.
But I am not getting the output which I use to get in for-loop.
This is my actual loop that get the perfect data in the form of array.
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mId);
}
same thing I tried using .map()
idArr = marray.map(function(row) {
return row[i].id;
});
But the actual array output is not coming.
It should be :
idArr = marray.map(function(row) {
return row.id;
});
row is the current value, not the entire array. So no need for the i.
Fiddle
Array.prototype.map()
Try using $.map() from jquery,
idArr = $.map(marray, function(v,i) {
return v.id;
});