Check if an object has a key in javascript - javascript

I have two arrays of objects, and I want to filter the first one according to whats on the second one. Here's an example:
var ary1 = [{id: 23, title: 'blabla'},{id:43, title: 'bleble'}, {id:54, title:'blibli'}];
var ary2 = [{id:23},{id:54}, {id:65}];
So in this case what I want to return is an array with the objects that have id's 23 and 54 of the first array, with all its possible properties (in this case, title).
Could you give me any hint that could help me?

Get a list of the indexes you want to search on using map:
var indexes = ary2.map(function (el) {
return el.id;
});
filter the results based on the list of indexes:
var result = ary1.filter(function (el) {
return indexes.indexOf(el.id) > -1;
});
DEMO

This might help you.
Loop through ary2, building up an array of each id value (let's call this array existingIds).
After that loop, now loop through ary1. For each item in ary1, check to see if the id value exists in the existingIds array that we just built up. If it does, append the current item to a result array.
I could write the code for you, but it will be a better learning experience if you first try this yourself :)

Might as well make use of some functional programming built into javascript.
filteredResults = ary1.filter(function(ele){
return (ary2.map(function(idobj){return idobj.id;}).indexOf(ele.id)>-1)
})
filter(function) will iterate through each element of an array, passing it through a callback function. From within that callback iff a true is returned, that value is kept. If false, that value is filtered out.
Also map(function) will iterate through each element of an array passing a callback value as well. All values returned from map callback will be injected into the result. So we can take the id from each element in ary2 and return it in the map function.
var ary1 = [{id: 23, title: 'blabla'},{id:43, title: 'bleble'}, {id:54, title:'blibli'}];
var ary2 = [{id:23},{id:54}, {id:65}];
//Filter for the available ID's, store the resulting objects in a new array
filteredResults = ary1.filter(function(ele){
//map creates an array of just ID's
return (ary2.map(function(idobj){return idobj.id;}).indexOf(ele.id)>-1)
})
//now do whatever you were planning on doing with your results/
var res = document.getElementById("results");
filteredResults.forEach(function(ele){
res.innerHTML+="<li>{id:"+ele.id + ",title:" +ele.title+"}</li>"
})
console.log(filteredResults);
<ul id="results"></ul>

try this:
var ary1 = [{id: 23, title: 'blabla'},{id:43, title: 'bleble'}, {id:54, title:'blibli'}];
var ary2 = [{id:23},{id:54}, {id:65}];
var newary=[];
for(x in ary1){
for(y in ary2){
if(ary1[x].id == ary2[y].id){
newary.push(ary1[x]);
}
}
}
console.log(newary);// here newary will be your return newary;

Related

.map() is storing unwanted undefined values into new array [duplicate]

This question already has answers here:
Why does JavaScript map function return undefined?
(13 answers)
Closed 3 years ago.
Simple array declaration:
let sodas = ["Sprite", "Coke", "Mountain Dew", "Dr. Pepper", "Sunkist"];
I want to use .map() function to create a new array containing sodas only owned by the CocaCola Company, and then display this new array in the console -
let cocacola_sodas = sodas.map(soda => {
if ((soda == "Coke") || (soda == "Sprite")) {
return soda;
}
})
console.log(cocacola_sodas);
This code seems to work, though I'm not sure why it is returning 5 new elements into cocacola_sodas array when only 2 of them should be returned (coke and sprite). The array will display ["Sprite", "Coke", undefined, undefined, undefined]. Why is it returning undefined values?
#awoldt, to help you understand what is actually happening, Array.prototype.map will always return the same number of elements from the input array to a new array.
so best way to think about it is you give map an array with x elements, regardless of what you do to those elements inside the block you pass to map, it will always return X # of elements in the new array.
As was suggested, something like filter/reduce will return a new array with just the elements that meet the criteria you set out int he block passed to those helpers
you can read more about map and all the Array.prototype.methods at MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Use filter instead of map. It was made or use in situations like this. As pointed by other answers map will always return the same number of elements as present in the input array
let sodas = ["Sprite", "Coke", "Mountain Dew", "Dr. Pepper", "Sunkist"];
let cocacola_sodas = sodas.filter(soda => {
if ((soda == "Coke") || (soda == "Sprite")) {
return soda;
}
})
console.log(cocacola_sodas);
To elaborate on #ellipsis answer:
The reason filter is better here is because it is generating a new array of items not filtered out of the original array.
The reason map is giving you the results you see are because it's not filtering, but changing each element and giving it to the result array. I think a code example would help to clarify.
Map might look something like this under the hood:
var array = ['one', 'two', three];
var mapFunc = function(item) {
if(item == 'two')
return item;
};
var mappedArray = [];
for(var i = 0; i < array.length; i++)
mappedArray.push(mapFunc(array[i]));
Obviously the above is simplified to be clear, but as you can see the mapped array will have as many items in it as the original array. Since you return nothing in the case item doesn't equal two then you return undefined hence why you have the extra items in your example.
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
let sodas = ["Sprite", "Coke", "Mountain Dew", "Dr. Pepper", "Sunkist"];
let cocaCola = ["Coke","Sprite"];
let cocacola_sodas = sodas.filter(soda => cocaCola.includes(soda))
console.log(cocacola_sodas);

Assign same key to values gotten from dynamic Array

I have an array received from backend: ["Drake","Ola","d"], now I need to assign all these values the same key which is id so it looks something like this:
[{id: "Drake"}, {id: "Ola"}, {id: "d"}]
I need a function to do this as the data is gotten after the page has loaded and I have tried many techniques including for loops.
I can also use JQuery if necessary, whats the solution please?
You could use Array#map and generate single objects with the wanted content.
The map() method creates a new array with the results of calling a provided function on every element in this array.
var data = ["Drake","Ola","d"],
result = data.map(function (a) { return { id: a }; });
console.log(result);
ES6
var data = ["Drake","Ola","d"],
result = data.map(a => ({ id: a }));
console.log(result);
Map should do the trick. Just create an object for each value with the id property being that value.
var array = ["Drake","Ola","d"];
var newArray = array.map(function(value){
return {id: value}
})
console.log(newArray);

Using the reduce function to return an array

Why is it that when I want to use the push function inside the reduce function to return a new array I get an error. However, when I use the concat method inside the reduce function, it returns a new array with no problem.
All I'm trying to do is pass an array to the reduce function and return the same array.
var store = [0,1,2,3,4];
var stored = store.reduce(function(pV,cV,cI){
console.log("pv: ", pV);
return pV.push(cV);
},[]);
This returns an error. But when I use concat:
var store = [0,1,2,3,4];
var stored = store.reduce(function(pV,cV,cI){
console.log("pv: ", pV);
return pV.concat(cV);
},[]);
It returns the same array.
Any ideas why?
push returns the new length of the array.
What you need is the initially provided array.
So change the code as below.
var store = [0, 1, 2, 3, 4];
var stored = store.reduce(function(pV, cV, cI){
console.log("pv: ", pV);
pV.push(cV);
return pV; // ********* Important ******
}, []);
concat returns the new array combining the elements of the provided array and concatenated elements. so it works.
Just for completeness, and for the next person who happens on this question, what you're doing is typically achieved with map which, as stated in the docs
map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results
Contrast that with the description of reduce:
The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
(Emphasis mine) So you see, although you can manipulate reduce to return a new array, it's general usage is to reduce an array to a single value.
So for your code this would be:
var store = [0,1,2,3,4];
var stored = store.map(function(pV){
console.log("pv: ", pV);
return pV;
});
Much simpler than trying to reconstruct a new array using either push or concat within a reduce function.
I know this is the same answer, but I just want to show that using reduce (), the syntax can also be reduced to a single line of code using ES6:
var store = [0,1,2,3,4];
var stored = store.reduce((pV,cV) => [...pV, cV], []);
console.log(stored);
reduce() can be useful if you need to return an array with multiple items for each item iterated:
var inputs = media.reduce((passedArray, video) => {
passedArray.push("-i");
passedArray.push(video.filepath);
return passedArray;
}, []);
Here it's being used to build the input array for FFmpeg;
[{ name: "bob", filepath: "1.mp4" }, { name: "sue", filepath: "3.mp4" }]
=> ["-i", "1.mp4", "-i", "2.mp4]
Array.prototype.push method returns the new length of the array.
Array.prototype.concat method inserts new element into array and returns array back so it can be further processed. This is what you need to do with reduce: pass modified array the the next iteration.
You can always use destructuring:
var store = [0,1,2,3,4];
var stored = store.reduce(function(pV,cV,cI){
console.log("pv: ", pV);
return [...pV, cV];
},[]);
console.log(stored);

Javascript map method on array of string elements

I am trying to understand how to implement the map method (rather than using a for loop) to check a string for palindromes and return boolean values for whether the mapped array elements reversed are the same as the original array elements. I cannot seem to understand the syntax of the map method. How do I get the map to function on each element in the original array? What is the value? Here is my working code, which is only logging a value of undefined:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.map(function (item) {
item.split("").reverse().join("");
return newArray === myArray;
});
}
console.log(palindromeChecker("What pop did dad Drink today"));
Here is a link to the fiddle:
https://jsfiddle.net/minditorrey/3s6uqxrh/1/
There is one related question here:
Javascript array map method callback parameters
but it doesn't answer my confusion about the syntax of the map method when using it to perform a function on an array of strings.
The map method will literally 'map' a function call onto each element in the array, take this as a simple example of increasing the value of each integer in an array by 1:
var items = [1,2,3];
items.map(function(item) {
return item + 1;
});
// returns [2,3,4]
In your case, you are trying to use map to accept or reject a string if it's a palindrome, so a simple implementation might be:
var items = ['mum', 'dad', 'brother'];
items.map(function(item) {
return item.split('').reverse().join('') === item;
});
// returns [true, true, false]
I'm not 100% sure of your reasons for using map, because if you were trying to just filter the array and remove the strings that aren't palindromes, you should probably use the filter method instead, which works in the same way, but would remove any that return false:
var items = ['mum', 'dad', 'brother'];
items.filter(function(item) {
return item.split('').reverse().join('') === item;
});
// returns ['mum', dad']
In your case you are splitting a string first to get your array of characters; you may also want to make that string lower case and remove punctuation, so an implementation might be:
var string = 'I live at home with my Mum, my Dad and my Brother!';
var items = string.toLowerCase().replace(/[^a-z0-9-\s]+/, '').split(' ');
items.filter(function(item) {
return item.split('').reverse().join('') === item;
});
// returns ['i', 'mum', dad']
As mentioned in one of the comments on your question, you need to ensure you return a value from your function if you are using a separate function to perform the check, so this is how your function should look:
function checkPalindromes(string) {
var items = string.toLowerCase().replace(/[^a-z0-9-\s]+/, '').split(' ');
items.filter(function(item) {
return item.split('').reverse().join('') === item;
});
return items;
}
And you would call it using:
checkPalindromes('I live at home with my Mum, my Dad and my Brother!'); // ['i', 'mum', 'dad']
try something like this:
let str = 'hello';
let tab = [...str];
tab.map((x)=> {
console.log("|"+x+"|");
return x;
})
newArray should include reversed version of theall items in myArray. After that, newArray should be reversed and joined with space in order to get the reversed version of the input string.
Here is the code:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.map(function (item) {
return item.split("").reverse().join("");
});
console.log(newArray);
return newArray.reverse().join(" ") === string;
}
console.log(palindromeChecker("dad did what"));
Javascript map method on array of string elements by using split() function.
let str = 'hello';
str.split('').map((x)=> {
console.log("|"+x+"|");
return x;
})
Map is a higher-order function available in ES5. I think your newArraywill contain an array of boolean values.
In essence, map will iterate over every value in your array and apply the function. The return value will be the new value in the array. You can also use map and save the information you need somewhere else, and ignore the result of course.
var arr = [1,2,3,4];
var newArray = arr.map(function(i) {
return i * 2;
});
//newArray = [2,4,6,8]
The map function in javascript (and pretty much in any language) is a great little function that allows you to call a function on each of the items on a list, and thus changing the list itself.
The (anonymous) function you're passing as an argument accepts an argument itself, which is filled by an item of the list it is working on, each time it is called.
So for a list [1,2,3,4], the function
function(item) { return item + 1 }, would give you a list of [2,3,4,5] for a result. The function you passed to $.map() is run over each element of the list, and thus changing the list.
So for your code: in the function you're passing as an argument to $.map(), you're returning whether the old and new array are equal (which is false btw). So since you're returning a boolean value, the list you'll end up with is a list of bools.
What I think you want to do, is extract the newArray == myArray from the function you're passing to $.map(), and putting it after your $.map() call.
Then inside the function you're passing to $.map(), return the item you're splitting and whatnot, so your newArray will be an array of strings like myArray.
Apart from a few minor mistakes in your code, such as scope issues (you're referencing the "newArray" and "myArray" outside of the function in which they where defined, and therefore, getting "undefined")..
The main issue you had is that you addressed the ENTIRE array inside the map function, while the whole concept is breaking things down to single elements (and then the function collects everything back to an array for you).
I've used the "filter" function in my example, because it works in a similar manner and I felt that it does what you wanted, but you can change the "filter" to a "map" and see what happends.
Cheers :)
HTML:
<body>
<p id="bla">
BLA
</p>
<p id="bla2">
BLA2
</p>
</body>
Javascript:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.filter(function (item) {
var reversedItem = item.split('').reverse().join('');
return item == reversedItem;
});
document.getElementById("bla").innerHTML = myArray;
document.getElementById("bla2").innerHTML = newArray;
}
palindromeChecker("What pop did dad Drink today");
Thanks for your input, all. This is the code I ended up with. I fixed the scope issues in the original post. My main problem was understanding the syntax of the map method. In particular, I could not understand from other online resources how to determine the value in the callback function. So, with much help from above I have placed the map method inside the palindromeChecker, and done all of the work on the array inside the map function.
var palindromeChecker = function(string) {
var newString = string.toLowerCase().split(' ');
newString.map(function(item) {
console.log(item.split('').reverse().join('') === item);
});
};
palindromeChecker("What pop did dad drink today");
//Returns false, true, true, true, false, false

jQuery.map - Practical uses for the function?

I am trying to get a better understanding of the jQuery.map function.
So in general terms .map takes a array and "maps" it to another array of items.
easy example:
$.map([0,1,2], function(n){
return n+4;
});
results in [4,5,6]
I think I understand what it does. I want to under why would someone need it. What is the practical use of this function? How are you using this in your code?
Mapping has two main purposes: grabbing properties from an array of items, and converting each item into something else.
Suppose you have an array of objects representing users:
var users = [
{ id: 1, name: "RedWolves" },
{ id: 2, name: "Ron DeVera" },
{ id: 3, name: "Jon Skeet" }
];
Mapping is a convenient way to grab a certain property from each item. For instance, you can convert it into an array of user IDs:
var userIds = $.map(users, function(u) { return u.id; });
As another example, say you have a collection of elements:
var ths = $('table tr th');
If you want to store the contents of those table headers for later use, you can get an array of their HTML contents:
var contents = $.map(ths, function(th) { return th.html(); });
$.map is all about converting items in a set.
As far as the DOM, I often use it to quickly pluck out values from my elements:
var usernames = $('#user-list li label').map(function() {
return this.innerHTML;
})
The above converts the <label> elements inside a list of users to just the text contained therein. Then I can do:
alert('The following users are still logged in: ' + usernames.join(', '));
Map is a high-order function, that enables you to apply certain function to a given sequence, generating a new resulting sequence containing the values of each original element with the value of the applied function.
I often use it to get a valid selector of all my jQuery UI panels for example:
var myPanels = $('a').map(function() {
return this.hash || null;
}).get().join(',');
That will return a comma separated string of the panels available in the current page like this:
"#home,#publish,#request,#contact"
And that is a valid selector that can be used:
$(myPanels);// do something with all the panels
Example:
$.map($.parseJSON(response), function(item) {
return { value: item.tagName, data: item.id };
})
Here server will be returning the "response" in JSON format, by using $.parseJSON it is converting JSON object to Javascript Object array.
By using $.map for each object value it will call the function(item) to display the result value: item.tagName, data: item.id
Here's one thing you could use it for.
$.map(["item1","item2","item3"], function(n){
var li = document.createElement ( 'li' );
li.innerHTML = n;
ul.appendChild ( li );
return li;
});
Recently I discovered an excellent example of .map in a practical setting.
Given the question of How to append options to a selectbox given this array (or another array):
selectValues = { "1": "test 1", "2": "test 2" };
this StackOverflow answer uses .map:
$("mySelect").append(
$.map(selectValues, function(v,k) {
return $("<option>").val(k).text(v);
})
);
Converting code values to code text would be a possible use. Such as when you have a select list and each indexed value has a corresponding code text.

Categories

Resources