For Loops for Name Property [duplicate] - javascript

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 4 years ago.
I am a very beginner with Javascript and I'm working on a question from my Mentor that I'm totally stuck on:
Create a function that accepts one parameter. This parameter will be an array of objects. Each object will have 1 property name. The function should return a new array that is populated with the name properties from the objects.
Example
namesFunction([{name: 'Tacos'},{name: 'Burritos'},{name: 'Enchiladas'}]);
//returns ['Tacos', 'Burritos', 'Enchiladas']
I do not know how to make a for loop that will iterate over any array put into the function parameters. I've only done ones that have defined arrays.
This is what I have:
function namesFunction(){
var arr = [];
for (i = 0; i < arr.length; i++){
console.log(arr[i].name);
}
}
namesFunction([{name: 'Tacos'},{name: 'Burritos'},{name: 'Enchiladas'}]);
Any help is appreciated! Thank you!

You're writing a function that takes an array:
function mapObjectsToNames(array) {}
And you want it to return a new array:
function mapObjectsToNames(array) {
var result = [];
return result;
}
You're going to have to iterate over each element in the array:
function mapObjectsToNames(array) {
var result = [];
for (var i = 0; i < array.length; i += 1) {
}
return result;
}
You already were logging the name property from each element:
function mapObjectsToNames(array) {
var result = [];
for (var i = 0; i < array.length; i += 1) {
console.log(array[i].name);
}
return result;
}
Now you'll want to add the name to the new list:
function mapObjectsToNames(array) {
var result = [];
for (var i = 0; i < array.length; i += 1) {
result.push(array[i].name);
}
return result;
}

Related

Two dimensional arrays populating does not work javascript

When i try to create two dimensional array in javascript using loop, it gives me following error:
Cannot set property 'indexis' of undefined
Code:
var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
indexes[i]['indexis'] = i;
indexes[i]['headingis'] = headingsArray[i]; //assuming headingsArray exist
indexes[i]['valueis'] = rows[0][i]; //assuming rows exist
}
}
You need to create the inner arrays/objects as well, or else index[i] is undefined, so index[i]['indexis'] will throw an exception.
var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
indexes[i] = {}; //<---- need this
if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
indexes[i]['indexis'] = i;
indexes[i]['headingis'] = headingsArray[i];
indexes[i]['valueis'] = rows[0][i];
}
}
You described it as a multidimensional array, but you're using it as though it's an array of objects (because you're accessing named properties, instead of numbered properties). So my example code is creating objects on each iteration. If you meant to have an array of arrays, then do indexes[i] = [], and interact with things like indexes[i][0] rather than indexes[i]['indexis']
You need an object before accessing a property of it.
indexes[i] = indexes[i] || {}
indexes[i]['indexis'] = i;
define temp var with field initialise to null & use push() function of JavaScript
for (var i = 0; i < headingsArray.length; i++) {
var temp={indexis: null,headingis:null,valueis:null};;
if (headingsArray) {
temp['indexis'] = i;
temp['headingis'] = headingsArray[i]; //assuming headingsArray exist
temp['valueis'] = rows[0][i];
indexes.push(temp);
}
}

Count how many strings in an array have duplicates in the same array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Array value count javascript
I have an array which contains several duplicates, what I'm trying to achieve is to count how many duplicates each unique string has in this one array.
The array looks something like this
array = ['aa','bb','cc','aa','ss','aa','bb'];
Thus I would like to do something like this
if (xWordOccurrences >= 5) {
// do something
}
But I'm not sure how I would code this.
I was thinking, create an object with each unique string, then loop through the original array, match each string with it's object and increment it's number by 1, then loop over the object to see which words had the most duplicates...
But this seems like an over complexe way to do it.
You can use an object which has keys of the Array's values and do something like this
// count everything
function getCounts(arr) {
var i = arr.length, // var to loop over
obj = {}; // obj to store results
while (i) obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
return obj;
}
// get specific from everything
function getCount(word, arr) {
return getCounts(arr)[word] || 0;
}
getCount('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
If you only ever want to get one, then it'd be more a bit more efficient to use a modified version of getCounts which looks similar to getCount, I'll call it getCount2
function getCount2(word, arr) {
var i = arr.length, // var to loop over
j = 0; // number of hits
while (i) if (arr[--i] === word) ++j; // count occurance
return j;
}
getCount2('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
Try this function:
var countOccurrences = function(arr,value){
var len = arr.length;
var occur = 0;
for(var i=0;i<len;i++){
if(arr[i]===value){
occur++;
}
}
return occur;
}
var count = countOccurrences(['aaa','bbb','ccc','bbb','ddd'],'bbb'); //2
If you want, you can also add this function to the Array prototype:
Array.prototype.countOccurrences = function(value){
var len = this.length;
var occur = 0;
for(var i=0;i<len;i++){
if(this[i]===value){
occur++;
}
}
return occur;
}
How about you build an object with named property?
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var summary = {};
var item = '';
for ( i in array){
item = array[i];
if(summary[item]){
summary[item] += 1;
}
else{
summary[item] = 1;
}
}
console.log( summary );
summary will contain like this
{aa: 3, bb: 2, cc: 1, ss: 1}
which you could then iterate on and then sort them later on if needed.
finally to get your count, you could use this summary['aa']
<script type="text/javascript">
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var myMap = {};
for(i = 0; i < array.length; i++) {
var count = myMap[array[i]];
if(count != null) {
count++;
} else {
count = 1;
}
myMap[array[i]] = count;
}
// at this point in the script, the map now contains each unique array item and a count of its entries
</script>
Hope this solves your problem
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var dups = {};
for (var i = 0, l = array.length; i < l; i++ ) {
dups[array[i]] = [];
}
for (str in dups) {
for (var i = 0, l = array.length; i < l; i++ ) {
if (str === array[i]) {
dups[str].push(str);
}
}
}
for (str in dups) {
console.log(str + ' has ' + (dups[str].length - 1) + ' duplicate(s)');
}
This function may do everything you need.
function countDupStr(arr, specifier) {
var count = {}, total = 0;
arr.forEach(function (v) {
count[v] = (count[v] || 0) + 1;
});
if(typeof specifier !== 'undefined') {
return count[specifier] - 1;
}
Object.keys(count).forEach(function (k) {
total += count[k] - 1;
});
return total;
}
Each value in the array is assigned and incremented to the count object. Whether or not a specifier was passed, the function will return duplicates of that specific string or the total number of duplicates. Note that this particular technique will only work on string-coercible values inside your arrays, as Javascript can only index objects by string.
What this means is that during object assignment, the keys will normalize down to strings and cannot be relied upon for uniqueness. That is to say, this function wouldn't be able to discern the difference between duplicates of 3 and '3'. To give an example, if I were to perform:
var o = {}, t = {};
o[t] = 1;
console.log(o);
The key used in place of t would eventually be t.toString(), thus resulting in the perhaps surprising object of {'[object Object]': 1}. Just something to keep in mind when working with Javascript properties.
I saw this post about it, perhaps it can help:
http://ryanbosinger.com/blog/2011/javascript-count-duplicates-in-an-array/

Removing duplicates in array of objects [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove duplicates from an array of objects in javascript
var arr = [{empID:100,empName:greg},{empID:101,empName:Math},{empID:100,empName:greg}];
var sorted_arr = arr.sort(); // You can define the comparing function here.
// JS by default uses a crappy string compare.
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
if (sorted_arr[i + 1].empID != sorted_arr[i].empID) {
results.push(sorted_arr[i]);
}
}
alert(results);
I have an array of objects, but when i try to remove the duplicate object which matches the ID, it does not get removed. What's the issue with the code.
Your code has two problems:
the sorting does not really work
you forget to add the last element to the result
I would suggest the following alternative:
var arr = ...;
arr.sort( function( a, b){ return a.empID - b.empID; } );
// delete all duplicates from the array
for( var i=0; i<arr.length-1; i++ ) {
if ( arr[i].empID == arr[i+1].empID ) {
delete arr[i];
}
}
// remove the "undefined entries"
arr = arr.filter( function( el ){ return (typeof el !== "undefined"); } );
Provided that empID is guaranteed to be a string or number, I would skip the sorting step and use an object as a hash of IDs that have already been seen:
var arr = [
{empID:100,empName:"greg"},
{empID:101,empName:Math},
{empID:100,empName:"greg"}
];
var results = [];
var idsSeen = {}, idSeenValue = {};
for (var i = 0, len = arr.length, id; i < len; ++i) {
id = arr[i].empID;
if (idsSeen[id] !== idSeenValue) {
results.push(arr[i]);
idsSeen[id] = idSeenValue;
}
}
Your sort function should really use a comparator, if you're going to be comparing items n and n+1
var sorted_arr = arr.sort(function(a,b) { return a.empID - b.empID; } );
This way you can be assured that sequential items in the list can possibly have duplicate empID properties.

How to use the "this" keyword to call a

How do I write a function in JavaScript that receives an array and a function(convertFunc). The function calls convertFunc for every element of the array.
The element should be accessed via the this keyword.
The function should return an array of the return values of the convertFunc calls?
e.g.
function(array, convertFunc() { // array=[1,2,3]
return this+10;
}
Should return [11,12,13]
Thanks
Create the function, e.g. function map(arr, convertFunc) {
Iterate over all elements of the array arr.
Tip: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call
Return an array containing all results from the function calls.
}
Figure the exact details out by yourself, good luck :)
array.map(callback[, thisObject]); might fit for you.
Example:
var nums = [1,2,3];
function FuncName(x)
{
return x+10;
}
var result = nums.map(FuncName); //[11,12,13]
Try this if you are looking for extending the Array object
Array.prototype.convertFunc = function() {
var arr = this, i; // As you want array is access using the this keyword.
for(i = 0; i<arr.length; i++)
{
arr[i] = arr[i] + 10;
}
return arr;
}
var myArray = [1,2,3];
// Call like this
myArray.convertFunc();
Fiddle here http://jsfiddle.net/PYxzj/
Update
And to answer your question try this
// Pass your array and a function as parameter
function arrayModify(array, convertFunc)
{
return array.convertFunc();
}
// This function iterates your array and adds 10 to each element.
var arrayAddFunction = function() {
var arr = this, i;
for(i = 0; i<arr.length; i++)
{
arr[i] = arr[i] + 10;
}
return arr;
}
// Extending the array object
Array.prototype.convertFunc = arrayAddFunction;
var aa = [1,2,3];
// As you want send your array and a function as parameters to another function
alert(arrayModify(aa,arrayAddFunction)); // -> [11, 12, 13]
Fiddle here http://jsfiddle.net/qzB4e/
var myFunc = function(fn) { // array=[1,2,3]
return fn(this);
};
myFunc.call(arr,function convertFunc(){
return this+10;
});
But, to solve your exact problem:
var arr = [1,2,3], addTen = function(){
for (var l=this.length;l--;) this[l] += 10;
};
addTen.call(arr);

Append an array to another array in JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
This question is an exact duplicate of:
How to append an array to an existing JavaScript Array?
How do you append an array to another array in JavaScript?
Other ways that a person might word this question:
Add an array to another
Concat / Concatenate arrays
Extend an array with another array
Put the contents of one array into another array
I spent some time looking for the answer to this question. Sometimes the simplest ones like these are the hardest to find answers to, so I am adding the question here hopefully with plenty of key words and phrases as per this blog post. Please feel free to answer this question with any other helpful information or edit the key words and phrases below.
If you want to modify the original array instead of returning a new array, use .push()...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply to push the individual members of arrays 2 and 3 at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
var array1 = ['a','b','c'];
var array2 = ['d','e','f'];
var array3 = ['g','h','i'];
array1.pushArrayMembers(array2, array3);
document.body.textContent = JSON.stringify(array1, null, 4);

Categories