I have data that is in an array, these are the ID's for users that have commented on said post. I want to compare this array with the id of the user, and if their id is in this array, continue with the code.
my array looks like:
({0:"1", 3:"6"}) // 1 and 6 are the ID's that I want to work with.
So I want to do something like:
var array = ({0:"1", 3:"6"});
var userID = 6;
if(in(array)==userID)
{
///you are in the list, so do whatever
}
Instancing your array like that will not create an array, but an object. Normally, you instantiate arrays in javascript like this:
var arr = [17, 4711];
Checking for a value using Array.indexOf:
arr.indexOf(17); // => 0
arr.indexOf(4711); // => 1
arr.indexOf(42); // => -1
Pushing:
arr.push(42);
arr.indexOf(42); // => 2
Array.indexOf is not in IE < 9, so I suggest you look into using a shim.
function inArray(needle, haystack) {
var count = 0;
for (var k in haystack) {
if (haystack.hasOwnProperty(k)) {
++count;
}
}
for (var i in haystack) {
if(haystack[i] == needle) return true;
}
return false;
}
See : http://jsfiddle.net/ryN6U/1/
If will not work with your object :)
You can loop through your object and check it against your userid. Something like
$(document).ready(function(){
var myArray = ({0:"1", 3:"6"});
var userId = 6;
for(vals in myArray){
if(userId == myArray[vals]){
alert("userid exists in array");
}
}
});
When testing against an array I would use jQuery's inArray()
if your looking for the first item in an object with a certain value look at this thread
json index of property value
Related
This question already has answers here:
Filter strings in Array based on content (filter search value)
(6 answers)
Closed 6 years ago.
I have a array in javascript containing "aassd,v_value1,asadds,v_value2, asddasd...", and I need extract the values that begin with v_ in a new array.
I used the next function to get the values, but only get the first value.
function search (array,string) {
var arr= [];
for (var i=0; i<array.length; i++) {
if (array[i].match(string)){
arr.push(i)
return arr;
}
}
return -1;
}
search(array,'v_')
Thanks.
You should use .filter() method as below:
function search (array,string) {
return array.filter(function (val) {
return val.substr(0, string.length) === string;
});
}
The filter() method returns items of array which fulfills the condition in the callback function
I think below might work. Just string match and push to new array if found.
var arr = ['aassd','v_value1','asadds','v_value2','asddasd'];
var newArr = []
substring = "v_";
for (var i = 0; i < arr.length; i++) {
if (arr[i].search(substring) === 0) {
newArr.push(arr[i]);
}
}
alert(newArr);
function search (array,string) {
var arr= [];
for (var i=0; i<array.length; i++) {
//Do not use MATCH here as you need values that STARTS WITH "v_", match will give you values like this asdasdav_asdasda also.
if (array[i].startsWith(string)){
//instead of this
//arr.push(i)
//use this , the above will push the index, this will push the VALUE(as asked in the question)
arr.push(array[i])
//remove this: as this breaks on the first true condition , hence you get one value.
//return arr;
}
}
return arr;
}
The Mistakes
Do not use MATCH for it will return values with the pattern anywhere in the string.
Use startsWith instead
Return outside the loop as it ends the loop when it matches the first time and hence you get only the first item
You should push the value not the index as asked in the question. So do this arr.push(array[i])
I am trying to create a JavaScript function that takes an array as a parameter and returns the first item in the array. This should work for an array of any size. Here is what I have so far, it appears to work just fine in the console but my instructor says there's a better way to do this:
var array = [];
function numbaOne(array) {
for (var i = 0; i < array.length; i++) {
console.log(array[0])
};
}
Any help would be appreciated. I've read about data structures and arrays but can't figure out how to simplify or make this better.
What you are doing is looping over the array and printing out the first item each time. You just want:
var array = [...];
function numbaOne(array) {
console.log(array[0]); // Print out the first value of the array
return array[0]; // Return the first value of the array
}
There is one edge case here. If the array is empty, then the function will fail because array[0] will be undefined.
So, a more complete version might be:
var array = [...];
function numbaOne(array) {
if(array.length > 0) { // Check if there is anything in the array
console.log(array[0]);
return array[0];
} else { // If there isn't, let's return something "bad"
console.log("The array is empty!");
return undefined;
}
}
I have an array of objects which contain certain duplicate properties: Following is the array sample:
var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];
So what i need is to merge the objects with same values of x like the following array:
var jsonData = [{x:12, machine1:7, machine2:8}, {x:15, machine2:7}]
I like the lodash library.
https://lodash.com/docs#groupBy
_.groupBy(jsonData, 'x') produces:
12: [ {x=12, machine1=7}, {x=12, machine2=8} ],
15: [ {x=15, machine2=7} ]
your desired result is achieved like this:
var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];
var groupedByX = _.groupBy(jsonData, 'x');
var result = [];
_.forEach(groupedByX, function(value, key){
var obj = {};
for(var i=0; i<value.length; i++) {
_.defaults(obj, value[i]);
}
result.push(obj);
});
I'm not sure if you're looking for pure JavaScript, but if you are, here's one solution. It's a bit heavy on nesting, but it gets the job done.
// Loop through all objects in the array
for (var i = 0; i < jsonData.length; i++) {
// Loop through all of the objects beyond i
// Don't increment automatically; we will do this later
for (var j = i+1; j < jsonData.length; ) {
// Check if our x values are a match
if (jsonData[i].x == jsonData[j].x) {
// Loop through all of the keys in our matching object
for (var key in jsonData[j]) {
// Ensure the key actually belongs to the object
// This is to avoid any prototype inheritance problems
if (jsonData[j].hasOwnProperty(key)) {
// Copy over the values to the first object
// Note this will overwrite any values if the key already exists!
jsonData[i][key] = jsonData[j][key];
}
}
// After copying the matching object, delete it from the array
// By deleting this object, the "next" object in the array moves back one
// Therefore it will be what j is prior to being incremented
// This is why we don't automatically increment
jsonData.splice(j, 1);
} else {
// If there's no match, increment to the next object to check
j++;
}
}
}
Note there is no defensive code in this sample; you probably want to add a few checks to make sure the data you have is formatted correctly before passing it along.
Also keep in mind that you might have to decide how to handle instances where two keys overlap but do not match (e.g. two objects both having machine1, but one with the value of 5 and the other with the value of 9). As is, whatever object comes later in the array will take precedence.
const mergeUnique = (list, $M = new Map(), id) => {
list.map(e => $M.has(e[id]) ? $M.set(e[id], { ...e, ...$M.get(e[id]) }) : $M.set(e[id], e));
return Array.from($M.values());
};
id would be x in your case
i created a jsperf with email as identifier: https://jsperf.com/mergeobjectswithmap/
it's a lot faster :)
I found a solution to where I get returned an array of elements without duplicates:
Array1 = Array1.filter(function(val) {
return Array2.indexOf(val) == -1;
});
However, I want to modify this code just a little bit. Instead of being returned an array without duplicates, I want to do something when there is a duplicate. The problem is, I'm not sure how exactly this code works. The thing is I'm not sure how val gets set, or what it even is.
for (var i = 0; i < json.length; i++) {
var item = json[i];
// if json.indexOf(val?), do something
}
Read the docs for the Array filter method then. The val parameter of the callback will be passed the single array items, i.e. json[i] or item in your case:
for (var i = 0; i < json.length; i++) {
var item = json[i];
if (json.indexOf(item) >= 0) {
// do something
}
}
var newArray = array1.filter(function(v, i) {
return array1.indexOf(v) == i;
});
This will return only unique itesm from array1;
array1.filter(function(v, i) {
// write your code here ('v' is individual value and 'i' is its index)
// don't return any anything if you don't want unique array to be returned.
// 'array1.indexOf(v) == i' checks if current value is duplicate from previous any values.
// try putting console.log on values you don't understand like (console.log(v,i) for values of 'v' and 'i')
return array1.indexOf(v) == i;
});
and off-curse you can loop an array with for loop as
for(i in array1){
// where i is index of array1, to get current value use array1[i]
if(array2.indexOf(array1[i]) >= 0){
// do something
}
console.log(i);
}
val is set by Array.prototype.filter, which calls the callback function on each element in the array. Since you don't want to filter you can use Array.prototype.forEach instead, which also calls the callback function once for each element in the array:
Array1.forEach(
// This function is called once per element in Array1
function(val){
if(Array2.indexOf(val) != -1){ // Check if that element is also in Array2
// `val` is in both arrays,
// Do something with it
}
}
);
You can utilize some modern libraries... like underscorejs.
Intersection is what you're looking for i guess: http://underscorejs.org/#intersection
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]
So your code may be something like
if(_.insersection(arr1, arr2)){
//since [] array is Falsy in JS this will work as a charm
}
From MDN: indexOf
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
From MDN: filter
Creates a new array with all elements that pass the test implemented by the provided function.
The first function works by returning true when an item from array1 isn't found in array2 (== -1). i.e.: Iterate through A and add anything not found in B.
So, to change to return only duplicates return true for anything that is found in both:
Array1 = Array1.filter(function(val) {
return Array2.indexOf(val) >= 0;
});
Array1 now contains only items with duplicates.
I have an array of objects in javascript. I use jquery.
How do i get the first element in the array? I cant use the array index - as I assign each elements index when I am adding the objects to the array. So the indexes arent 0, 1, 2 etc.
Just need to get the first element of the array?
If you don't use sequentially numbered elements, you'll have to loop through until you hit the first one:
var firstIndex = 0;
while (firstIndex < myarray.length && myarray[firstIndex] === undefined) {
firstIndex++;
}
if (firstIndex < myarray.length) {
var firstElement = myarray[firstIndex];
} else {
// no elements.
}
or some equivalently silly construction. This gets you the first item's index, which you might or might not care about it.
If this is something you need to do often, you should keep a lookaside reference to the current first valid index, so this becomes an O(1) operation instead of O(n) every time. If you're frequently needing to iterate through a truly sparse array, consider another data structure, like keeping an object alongside it that back-maps ordinal results to indexes, or something that fits your data.
The filter method works with sparse arrays.
var first = array.filter(x => true)[0];
Have you considered:
function getFirstIndex(array){
var result;
if(array instanceof Array){
for(var i in array){
result = i;
break;
}
} else {
return null;
}
return result;
}
?
And as a way to get the last element in the array:
function getLastIndex(array){
var result;
if(array instanceof Array){
result = array.push("");
array.pop;
}
} else {
return null;
}
return result;
}
Neither of these uses jquery.
Object.keys(array)[0] returns the index (in String form) of the first element in the sparse array.
var array = [];
array[2] = true;
array[5] = undefined;
var keys = Object.keys(array); // => ["2", "5"]
var first = Number(keys[0]); // => 2
var last = Number(keys[keys.length - 1]); // => 5
I was also facing a similar problem and was surprised that no one has considered the following:
var testArray = [];
testArray [1245]= 31;
testArray[2045] = 45;
for(index in testArray){
console.log(index+','+testArray[index])
}
The above will produce
1245,31
2045,45
If needed you could exist after the first iteration if all that was required but generally we need to know where in the array to begin.
This is a proposal with ES5 method with Array#some.
The code gets the first nonsparse element and the index. The iteration stops immediately with returning true in the callback:
var a = [, , 22, 33],
value,
index;
a.some(function (v, i) {
value = v;
index = i;
return true;
});
console.log(index, value);
If you find yourself needing to do manipulation of arrays a lot, you might be interested in the Underscore library. It provides utility methods for manipulating arrays, for example compact:
var yourArray = [];
yourArray[10] = "foo";
var firstValue = _.compact(yourArray)[0];
However, it does sound like you are doing something strange when you are constructing your array. Perhaps Array.push would help you out?