Want to search string in the array of objects? - javascript

I want to search this employee array which is consisted of objects and i should be able to search any text like if i pass ---> search_for_string_in_array ('aaron', employees) ; it should display me 'Value exists in array' or if its the way please help me..
//here is the employeee array ...
var employees =[{
name:"jacob",
age :23,
city:"virginia",
yoe :12,
image :'a.jpg'
},
{
name:"aaron",
age :21,
city:"virginia",
yoe :12,
image :'b.jpg'
},
{
name:"johnny",
age :50,
city:"texas",
yoe :12,
image :'c.jpg'
},
{
name:"jacob",
age :12,
city:"virginia",
yoe :12,
image :'a.jpg'
}];
here is the function which performs searching functionality inside an array.
function search_for_string_in_array(search_for_string, employees)
{
for (var i=0; i < employees.length; i++)
{
if (employees[i].match(search_for_string))
{
return 'Value exists in array';
}
}
return 'Value does NOT exist in array';
}
Simply pass the value to search for and the array to the function and it will tell you whether the string exists as a part of an array value or not.

If you know the structure of the Array, you should probably just loop through it and test each value. If you don’t know the structure, you can stringify the array into JSON and regexp it (although it won’t be as safe):
function search_for_string_in_array(str, arr) {
var json = JSON.stringify(arr);
return new RegExp(':\"'+str+'\"','g').test(json);
}

just replace the line
if (employees[i].match(search_for_string))
with this:
if (employees[i].name.match(search_for_string))

Try
function search(text) {
text += '';
var i, obj;
var array = [];
for (i = 0; i < employees.length; i++) {
var obj = employees[i];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (('' + obj[key]).indexOf(text) >= 0
|| ('' + key).indexOf(text) >= 0) {
array.push(obj);
break;
}
}
}
}
return array.length > 0;
}
Demo: Fiddle1 Fiddle2

Related

How to concatenate values of duplicate keys

When reading a csv into a javascript dictionary, how can I concatenate values of what would otherwise be duplicate keys? I've seen answers for how to do this with bash, c#, and perl, but I haven't been able to find answers for Javascript. Here's what I have:
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
subjects[data[i].Id] = data[i].VALUE;
}
console.log(subjects);
});
This, obviously writes over existing keys. Instead, I want the key to be an array of the values. The csv basically looks like:
Id, VALUE
id1, subject1
id2, subject1
id1, subject3
And I want to output as:
{"id1": ["subject1", "subject3"], "id2": ["subject1"]...}
Just check if your output already has the key, if so you add the new value to the array. Else you create an array.
d3.csv("test.csv", function(data) {
var subjects = {};
for (var i = 0; i < data.length; i++)
{
// Check if key already exists
if(subjects.hasOwnProperty(data[i].Id)){
// push data to array
subjects[data[i].Id].push(data[i].VALUE);
}else{
// create new key and array
subjects[data[i].Id] = [data[i].VALUE];
}
}
console.log(subjects);
});
You could make it into an array and then push the content into that array
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
//first time we see this id, turn it into an array
if(typeof subjects[data[i].Id] != "object"){
subjects[data[i].Id] = [];
}
//push content to the array
subjects[data[i].Id].push(data[i].VALUE);
}
console.log(subjects);
});
Try this inside the for loop:
typeof subjects[data[i].Id] == 'undefined' && (subjects[data[i].Id] = []);
subjects[data[i].Id].push(data[i].VALUE);
You can reduce the footprint of your code slightly if you use reduce:
var out = data.reduce((p, c) => {
const id = c.Id;
p[id] = p[id] || [];
p[id].push(c.VALUE);
return p;
}, {});
RESULT
{
"id1": [
"subject1",
"subject3"
],
"id2": [
"subject1"
]
}
DEMO

Get full value from array using partial value

I have an array like this:
var array = ["xs-1", "sm-10", "md-4"];
Now I want to get the number at the end of a particular value. For example I want to search the array for "md-" and see what number is at the end of that string (should return 4).
I can't do array.indexOf("xs-") because that isn't the whole value. Is there a way to do this?
Using a for loop:
var array = ["xs-1", "sm-10", "md-4"];
var search = "md-";
var found = null;
for (var i = 0; i < array.length; i++) {
if (array[i].indexOf(search) === 0) {
found = array[i];
break; // Note: this is assuming only one match exists - or at least you are
// only interested in the first match
}
}
if (found) {
alert(found);
} else {
alert("Not found");
}
Using .filter:
var array = ["xs-1", "sm-10", "md-4"];
var search = "md-";
var filtered = array.filter(function(item) {
return item.indexOf(search) === 0;
});
// note that here filtered will contain all matched elements, so it might be more than
// one match.
alert(filtered);
Building from #János Weisz's suggestion, you can easily transform your array into an object using .reduce:
var array = ["xs-1", "sm-10", "md-4"];
var search = "md";
var obj = array.reduce(function(prev, item) {
var cells = item.split("-");
prev[cells[0]] = cells[1];
return prev;
}, {});
// note: at this point we have an object that looks like this:
// { xs:1, sm:10, md: 4 }
// if we save this object, we can do lookups much faster than looping
// through an array
// now to find "md", we simply do:
alert(obj[search]);
If you need to do multiple look ups from the same source array, then transforming it into an object may be the most efficient approach overall. You pay the initial price of the transformation, but after than lookups are O(1) versus O(n) for each time you have to search your array. Of course, if you only ever need one item, then probably don't bother.
I recommend using objects for this:
var array = [{'type': 'xs', 'value': 1}, {'type' : 'sm', 'value': '10'}, {'type' : 'md', 'value': '4'}];
This way you can search the array as:
function searchMyArrayByType(array, type) {
var items[];
for (var i = 0; i < array.length; i++)
{
if (array[i].type == type) items.push(array[i].value);
}
return items;
}
var valuesWithMd = searchMyArrayByType(array, 'md');
For more information regarding the structure and use of objects, please refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
You can create a method that takes the prefix you're looking for, the array, and the split character and returns all the numbers in an array:
function findNumberFromPrefix(prefix, arr, splitChar) {
var values = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf(prefix) === 0) {
values.push(arr[i].split(splitChar)[1]);
}
}
return values;
}
And call it:
var array = ["xs-1", "sm-10", "md-4"];
var values = findNumberFromPrefix("md-", array, "-");
console.log(values); //["4"]
Demo: http://jsfiddle.net/rn4h9msh/
A more functional approach and assuming you can have have more than one element with the same prefix:
function findPrefix(array, prefix) {
return array.filter(function (a) { return a.indexOf(prefix) === 0; })
.map(function (e) { return e.slice(prefix.length); })
}
If you have only one matching element, do a loop like this:
var array = ["xs-1", "sm-10", "md-4"];
var needle = "md-";
for(i=0;i<array.length;i++) {
if(array[i].indexOf(needle) == 0)
alert(array[i].substr(needle.length, array[i].length));
}
Demo: http://jsfiddle.net/kg0c43ov/
You can do it like this...
var array = ["xs-1", "sm-10", "md-4"];
getValue("md-");
function getValue(search) {
for(var key in array) {
if(array[key].indexOf(search) > -1) {
alert("Array key is: " + key);
alert("Array value is: " + array[key].replace(search, ""));
}
}
}
JSFiddle here.

remove duplicated value from array and replace it with the latest value in javascript

I have an array in JavaScript. The user enters string and the data placed in this array in the form of value and name.
if(!_.isUndefined(args[1]) && !_.isUndefined(args[2])) {
if(args[1].length !== 0 && args[2].length !== 0) {
var dataObj = {
name : args[1],
value : args[2]
};
formateArray.push({name: dataObj.name, value:dataObj.value});
How can I remove duplicated value from array and replace it with the latest value the user enters?
So when the user enters: value_1 100, value_2 200, value_1 500
I expect to see: value_1 500, value_2 200 (replace the duplicates with new data)
You can iterate your array replace the value if the name already exists.
function push(array, newVal) {
var found = false;
for (var i = 0; i < array.length && !found; i++) {
if (array[i].name === newVal.name) {
array[i].value = newVal.value;
found = true;
}
}
if (!found) {
array.push(newVal);
}
}
function printNameValue(array) {
var out = '';
for (var i = 0; i < array.length; i++) {
out += array[i].name + ' ' + array[i].value + ', ';
}
return out;
}
var myArray = [];
push(myArray, {
name: 'value_1',
value: 100
});
push(myArray, {
name: 'value_2',
value: 200
});
push(myArray, {
name: 'value_1',
value: 500
});
alert(printNameValue(myArray));
Since your values can be associated with meaningful keys, perhaps you should use an object map rather than an array to store your values. Avoiding duplicates now becomes trivial since you cannot have duplicate keys.
var valuesMap = {};
//setting value
valuesMap.value_1 = 100;
//setting another value
valuesMap.value_2 = 200;
//replacing it
valuesMap.value_1 = 500;
Otherwise it's still quite simple, but less efficient:
function add(arr, obj) {
var key = obj.name, i, len;
for (i = 0, len = arr.length; i < len; i++) {
if (arr[i].name === key) {
arr[i] = obj;
return;
}
}
arr.push(obj);
}
var values = [];
add(values, { name: 'test', value: 1 });
add(values, { name: 'test', value: 2 });
values.length; //1
Instead of the array object, i suggest you to use an object that will act like a hashtable. You can define on this way var formateArray = {};
When you want to add or edit the data, instead of using push, you can do it like this:
formateArray[dataObj.name] = {name: dataObj.name, value:dataObj.value};
If the key does not exist dataObj.name, it will be added. It the key exist, the value would set with the new value.
If you want the size of you array, you get it this way Object.keys(formateArray).length
If you want to loop on your data, you can do it this way:
for (var k in formateArray) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (formateArray.hasOwnProperty(k)) {
alert('key is: ' + k + ', value is: ' + formateArray[k].value);
}
}
Here is a jsfiddle that illustrate this.

find the object index using id in json

I have a json that contains many objects:
[Object, Object, Object, ... ]
Inside each object there is an object number and an id:
0: Object
id: "theObjectImLookingFor"
...
How can I find the object number (0) using the id "theObjectImLookingFor" in javascript?
Try this:
function someFunc(){
var objArr = [Object, Object, Object, ... ];
for(var i = 0; i < objArr.length; i++){
if(objArr[i].id == "theObjectImLookingFor")
return i;
}
return "No value matched";
}
This assumes there's only one property with a numeric name. This is a very strange way to store something you want to be able to look up. Why not give each object an obj_number property?
function find_object(json, str) {
for (var i = 0; i < json.length; i++) {
if (json[i].id == str) {
for (var key in json[i]) {
if (IsNumeric(key)) {
return key;
}
}
}
}
return false; // Not found
}

Sum values of attribute when the value of an other attribute is the same

I have an array of objects like this one:
{'shapeId': 'shapeid1', 'latlong': '45.42342,-65.23424', 'number': 5}
I want the sum of the values of the attribute number when the value of the attribute shapeId is the same.
Is there a built in method for that? Thank you!
What I tried so far is this, using reduce() method, but the results are odd when the function is called many times.
function selectMarkersInPoly() {
allTotal = new Array();
alert(allMarkers.length)
for (var i=0; i < createdShapes.length; i++) {
for (var j=0; j < allMarkers.length; j++){
var latlong = allMarkers[j].getPosition();
if(google.maps.geometry.poly.containsLocation(latlong, createdShapes[i]) == true) {
allMarkers[j].setOptions({
icon : "http://labs.google.com/ridefinder/images/mm_20_white.png",
shapeId:createdShapes[i].id
});
}else{
allMarkers[j].setOptions({
icon : "http://labs.google.com/ridefinder/images/mm_20_red.png",
shapeId: 'shapeid0'
});
}
}
}
allTotal = allMarkers.reduce(function(res, obj) {
if (!(obj.shapeId in res)){
res.__array.push(res[obj.shapeId] = obj);
}else {
res[obj.shapeId].number += obj.number;
}
return res;
}, {__array:[]}).__array
.sort(function(a,b) { return b.shapeId - a.shapeId;
});
for (var j=0; j < allTotal.length; j++) {
alert(allTotal[j].shapeId + ': ' + allTotal[j].number)
}
}
There are 32600 numbers total in allMarkers.number among 3505 objects. The first time I call the function I get:
allTotal= [
Object { number=32598, shapeId='shapeid0'},
Object { number=2, shapeId='shapeid1'}
]
where shapeid0 is not selected. The second time I call the function without changing anything, I get:
allTotal= [
Object { number=65193, shapeId='shapeid0'},
Object { number=2, shapeId='shapeid1'}
]
And the third time:
allTotal= [
Object { number=97788, shapeId='shapeid0'},
Object { number=2, shapeId='shapeid1'}
]
Your code is a bit oddly formatted. However, the problem is that inside the expression res.__array.push(res[obj.shapeId] = obj); you assign the object itself to the res, not a clone. With res[obj.shapeId].number += obj.number; you then manipulate the original object, which is why the results grow in subsequent calls.
Better:
var numberSums = allMarkers.reduce(function(res, obj) {
var id = obj.shapeId;
if (id in res)
res[id] += obj.number;
else
res[id] = obj.number;
return res;
}, {});
Object.keys(numberSums).sort(function(a,b){return a-b;}).forEach(function(id) {
alert(id+": "+numberSums[id]);
});

Categories

Resources