I'm looking for a javascript implementation (for IE11) for this problem; my inputs are two arrays like these:
var array1 = [{id: 1, param:"bon jour"}, {id: 2, param:"Hi"}, {id: 3, param:"Hello"}];
var array2 = [{item: "Peter", values:"1,2", singlevalue:"2"},
{item: "Mark", values:"1,2,3", singlevalue:"3"},
{item: "Lou", values:"2", singlevalue:"2"}];
and I should create a new array (array3) with array2 data plus 2 new fields ("params" and "singleparam"), using matching between array1[i].id and array2[x].values to evaluate "params" and between array1[i].id and array2[x].singlevalue to evaluate "singleparam", with this kind of result:
array3 = [{item: "Peter", values:"1,2", singlevalue:"2", params:"bon jour,Hi", singleparam:"Hi"},
{item: "Mark", values:"1,2,3", singlevalue:"3", params:"bon jour,Hi,Hello", singleparam:"Hello"},
{item: "Lou", values:"2", singlevalue:"2", params:"Hi", singleparam:"Hi"}];
I'm a javascript newbie and I've tried this kind of solution:
var array3 = array2.map(function(x, array1)
{
const newOb = {};
newOb.item = x.item;
newOb.values = x.values;
newOb.singlevalue = x.singlevalue;
newOb.params = function(x.values, array1)
{
var str = "";
var idArray = x.values.split(",");
for(i = 0; i < idArray.lenght; i++)
{
for(j = 0; i < array1.lenght; j++)
{
if(idArray[i] == array1[j].id)
{
str += array1[j].param + ",";
break;
}
}
}
return str;
};
newOb.singleparam = function(x.singlevalue, array1)
{
var val;
for(j = 0; i < array1.lenght; j++)
{
if(array1[j].id == x.singlevalue)
val = array1[j].param;
}
return val;
}
return newOb;
});
console.log(array3);
with this error: Error: Unexpected token '.'
I'd like to find an efficient solution considering that array1 has less than 10 elements, but array2 could contains more than 1000 objects.
Thanks in advance for your support
I will skip the functions stop and singlevalues and there were also some syntax errors,
for example the correct one is length and not lenght
var array1 = [{id: 1, param:"bon jour"}, {id: 2, param:"Hi"}, {id: 3, param:"Hello"}];
var array2 = [{item: "Peter", values:"1,2", singlevalue:"2"},
{item: "Mark", values:"1,2,3", singlevalue:"3"},
{item: "Lou", values:"2", singlevalue:"2"}];
function newArray3() {
return array2.map(x => {
const newOb = {};
newOb.item = x.item;
newOb.values = x.values;
newOb.singlevalue = x.singlevalue;
newOb.params = paramsFunction(x.values, array1);
newOb.singleparam = singleParamFunction(x.singlevalue, array1);
return newOb;
})
}
function singleParamFunction(x, array1) {
var val;
for(i = 0; i < array1.length; i++) {
if(array1[i].id.toString() == x) {
val = array1[i].param;
}
}
return val;
}
function paramsFunction(x, array1) {
var str = "";
var idArray = x.split(",");
for(i = 0; i < idArray.length; i++)
{
for(j = 0; j < array1.length; j++)
{
if(idArray[i] == array1[j].id.toString())
{
str += array1[j].param + ",";
break;
}
}
}
return str;
}
array3 = newArray3();
console.log(array3)
The solution provided by the #Walteann Costa can show the desired results in other browsers but it will not work for the IE browser as his code sample uses the => Arrow functions that is not supported in the IE browser.
As your question asks the solution for the IE browser, I tried to modify the code sample provided by the #Walteann Costa. Below modified code can work with the IE 11 browser.
<!doctype html>
<html>
<head>
<script>
"use strict";
var array1 = [{
id: 1,
param: "bon jour"
}, {
id: 2,
param: "Hi"
}, {
id: 3,
param: "Hello"
}];
var array2 = [{
item: "Peter",
values: "1,2",
singlevalue: "2"
}, {
item: "Mark",
values: "1,2,3",
singlevalue: "3"
}, {
item: "Lou",
values: "2",
singlevalue: "2"
}];
function newArray3() {
return array2.map(function (x) {
var newOb = {};
newOb.item = x.item;
newOb.values = x.values;
newOb.singlevalue = x.singlevalue;
newOb.params = paramsFunction(x.values, array1);
newOb.singleparam = singleParamFunction(x.singlevalue, array1);
return newOb;
});
}
function singleParamFunction(x, array1) {
var val,i,j;
for (i = 0; i < array1.length; i++) {
if (array1[i].id.toString() == x) {
val = array1[i].param;
}
}
return val;
}
function paramsFunction(x, array1) {
var str = "";
var idArray = x.split(",");
var i,j;
for (i = 0; i < idArray.length; i++) {
for (j = 0; j < array1.length; j++) {
if (idArray[i] == array1[j].id.toString()) {
str += array1[j].param + ",";
break;
}
}
}
return str;
}
var array3 = newArray3();
console.log(array3[0]);
console.log(array3[1]);
console.log(array3[2]);
</script>
</head>
<body>
</body>
</html>
Output in the IE 11:
Related
If I populate an array of pairs (inside a get json) like so:
var arrItems = [];
for (let y=0; y<50 ;y++){
var titl = data.item[y].name;
var img = data.item[y].image[0].url;
arrItems.push({t:titl,i:img});
}
How can I then filter it to leave only 3 pairs where value is the same?
Example:
arrItems = [
{t:one,i:square.jpg},
{t:two,i:square.jpg},
{t:three,i:square.jpg},
{t:four,i:square.jpg},
{t:five,i:triangle.jpg}
];
Becomes
arrItems = [
{t:one,i:square.jpg},
{t:two,i:square.jpg},
{t:three,i:square.jpg},
{t:five,i:triangle.jpg}
];
Both JavaScript or jQuery are OK.
You could take a hash table and count the occurences of the wanted property and filter with a max value.
var items = [{ t: 'one', i: 'square.jpg' }, { t: 'two', i: 'square.jpg' }, { t: 'three', i: 'square.jpg' }, { t: 'four', i: 'square.jpg' }, { t: 'five', i: 'triangle.jpg' }],
count = {},
result = items.filter(({ i }) => {
count[i] = (count[i] || 0) + 1;
return count[i] <= 3;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
There might be some more efficient ways to write it, but I would think the easiest to understand is the straightforward iteration with counting:
var counts = {};
for (var i = 0; i < arrItems.length; i++) {
var item = arrItems[i];
var count = counts[item.i] || 0;
if (count >= 3) {
arrItems.splice(i, 1);
i--;
} else {
counts[item.i] = ++count;
}
}
You can use reduce function
var arrItems = [
{t:'one',i:'square.jpg'},
{t:'two',i:'square.jpg'},
{t:'three',i:'square.jpg'},
{t:'four',i:'square.jpg'},
{t:'five',i:'triangle.jpg'}
];
var output = arrItems.reduce((acc, {t,i})=>{
acc['mem'][i] = (acc['mem'][i] || 0) + 1;
acc['mem'][i] <= 3 ? acc['output'].push({t, i}) : '';
return acc;
}, {'mem':{}, 'output':[]});
console.log(output);
I have an array store Task information. Each task has also an array of taskId that it is depending on.
Input
let inputArr = [
{
id: 1,
dependOnTasks: [2, 3]
},
{
id: 2,
dependOnTasks: [3]
},
{
id: 3,
dependOnTasks: []
},
{
id: 4,
dependOnTasks: [5]
},
{
id: 5,
dependOnTasks: []
},
{
id: 6,
dependOnTasks: [5]
}
]
The expected output is grouping all the depending task into one array for displaying into the UI.
Output
[
[
{
id: 1,
dependOnTasks: [2, 3]
},
{
id: 2,
dependOnTasks: [3]
},
{
id: 3,
dependOnTasks: []
}
],
[
{
id: 4,
dependOnTasks: [5]
},
{
id: 5,
dependOnTasks: []
},
{
id: 6,
dependOnTasks: [5]
}
]
]
I have made a function to do it but seem I was thinking wrong by hard-coded it. Hope someone can help me archive it right way using pure JavaScript/TypeScript or Underscore since we have already used in the project.
Noted: TaskId will be random string like "5878465507b36e1f9c4c46fe"
// will contain the groups (results).
var result = [];
// will serve as a holder of the already treated indexes of inputArr.
var indexCache = [];
// insert obj into a group, insert its dependencies and the object that depend on it as well.
function insertWithDependencies(obj, group){
// insert this obj into this group
group.push(obj);
// First: look for the objects it depends on
obj.dependOnTasks.forEach(function(id){
for(var i = 0; i < inputArr.length; i++){
// if the object in this index is already treated, then ignore it
if(indexCache.indexOf(i) != -1) continue;
// if this object is a dependency of obj then insert it with its own dependencies.
if(inputArr[i].id == id){
var o = inputArr[i];
indexCache.push(i); // cache this i as well
insertWithDependencies(o, group);
}
}
});
// Then: look for the objects that depends on it
for(var i = 0; i < inputArr.length; i++){
// if the object in this index is already treated, then ignore it
if(indexCache.indexOf(i) != -1) continue;
// if this object depends on obj then insert it with ...
if(inputArr[i].dependOnTasks.indexOf(obj.id) != -1){
var o = inputArr[i];
indexCache.push(i); // cache i
insertWithDependencies(o, group);
}
}
};
// while there is element in the inputArr that haven't been treated yet
while(inputArr.length != indexCache.length){
// the group that will hold the depending tasks all together
var group = [];
// look for the first untreated object in inputArr
var i;
for(i = 0; i < inputArr.length; i++)
if(indexCache.indexOf(i) == -1)
break;
var obj = inputArr[i];
// cache its index
indexCache.push(i)
// insert it along its dependencies
insertWithDependencies(obj, group);
// push the group into the result array
result.push(group);
}
ANOTHER WAY:
Here is an optimised way to do it, but the data inside inputArr will be lost afterwards. It won't use the indexCache to see if an index is already treated or not but instead it will make all treated items null in inputArr. So if you don't care or won't use inputArr afterwards, use this instead:
var result = [];
function insertWithDependencies(obj, group){
group.push(obj);
obj.dependOnTasks.forEach(function(id){
for(var i = 0; i < inputArr.length; i++){
if(!inputArr[i]) continue;
if(inputArr[i].id == id){
var o = inputArr[i];
inputArr[i] = null;
insertWithDependencies(o, group);
}
}
});
for(var i = 0; i < inputArr.length; i++){
if(!inputArr[i]) continue;
if(inputArr[i].dependOnTasks.indexOf(obj.id) != -1){
var o = inputArr[i];
inputArr[i] = null;
insertWithDependencies(o, group);
}
}
};
function findNotNull(){
for(var i = 0; i < inputArr.length; i++)
if(inputArr[i]) return i;
return -1;
}
var index;
while((index = findNotNull()) != -1){
var group = [];
var obj = inputArr[index];
inputArr[index] = null;
insertWithDependencies(obj, group);
result.push(group);
}
console.log(result);
The solution is straightforward,
Initialize empty group list
For each task find if there is a group in the group list with id or id of any dependent tasks
If not add a new group with task id and dependent tasks
var input = [
{ id: 1, dependOnTasks: [2, 3] },
{ id: 2, dependOnTasks: [3] },
{ id: 3, dependOnTasks: [] },
{ id: 4, dependOnTasks: [5] },
{ id: 5, dependOnTasks: [] },
{ id: 6, dependOnTasks: [5] }
];
var groups = [];
for (var i = 0; i < input.length; i++){
var group = findGroup(groups,input[i]);
if (!group){
group = {ids : []};
group.ids.push(input[i].id);
groups.push(group);
}
if (group.ids.indexOf(input[i].id) === -1){
group.ids.push(input[i].id);
}
for (var j = 0; j < input[i].dependOnTasks.length; j++){
if (group.ids.indexOf(input[i].dependOnTasks[j]) === -1){
group.ids.push(input[i].dependOnTasks[j]);
}
}
}
document.write(groups[0].ids + '</br>');
document.write(groups[1].ids + '</br>');
function findGroup(groups,task){
for (var i = 0; i < groups.length; i++){
var group = groups[i];
if (group.ids.indexOf(task.id) !== -1){
return group;
}
for (var j = 0; j < task.dependOnTasks.length; j++){
if (group.ids.indexOf(task.dependOnTasks[j]) !== -1){
return group;
}
}
}
return null;
}
If you don't care about the order of the tasks in the same group. Using union and find to implement a disjoint set might be an option.
Util data structure:
function UnionFind(n) {
this.parent = [...Array(n+1).keys()]
}
UnionFind.prototype.find = function(x) {
if (this.parent[x] === x) {
return x
}
const ret = this.find(this.parent[x])
this.parent[x] = ret
return ret
}
UnionFind.prototype.union = function(x, y) {
let x_rep = this.find(x)
let y_rep = this.find(y)
if (x_rep !== y_rep) {
this.parent[x_rep] = y_rep
}
}
Dumb data source:
let inputArr = [
{
id: 1,
dependOnTasks: [2, 3]
},
{
id: 2,
dependOnTasks: [3]
},
{
id: 3,
dependOnTasks: []
},
{
id: 4,
dependOnTasks: [5]
},
{
id: 5,
dependOnTasks: []
},
{
id: 6,
dependOnTasks: [5]
}
]
Driver program:
let len = inputArr.length
let uf = new UnionFind(len)
// iterate through all tasks to group them
inputArr.forEach(entry => {
entry.dependOnTasks.forEach(depsId => {
uf.union(entry.id, depsId)
})
})
// reiterate to retrieve each task's group and group them using a hash table
let groups = {}
inputArr.forEach(entry => {
const groupId = uf.find(entry.id)
if (!groups.hasOwnProperty(groupId)) {
groups[groupId] = [entry]
return
}
groups[groupId].push(entry)
})
let result = Object.keys(groups).map(groupId => groups[groupId])
console.log(JSON.stringify(result, null, 2))
note: if id is random string in your case, simply change this.parent to hash map, and if you care about the order(as there're dependency trees), consider using topological sort instead.
You can try with my code
var inputArr = [
{
id: 1,
dependOnTasks: [2, 3]
},
{
id: 2,
dependOnTasks: [3]
},
{
id: 3,
dependOnTasks: []
},
{
id: 4,
dependOnTasks: [5]
},
{
id: 5,
dependOnTasks: []
},
{
id: 6,
dependOnTasks: [5]
}
]
// make matrix graph
var map = {};
for (var i = 0; i < inputArr.length; i++) {
var task = inputArr[i];
map[task.id] = map[task.id] || {};
for (var j = 0; j < task.dependOnTasks.length; j++) {
var dependId = task.dependOnTasks[j];
map[dependId] = map[dependId] || {};
map[task.id][dependId] = true;
map[dependId][task.id] = true;
}
}
var groupTasks = [];
for (var key in map) {
var group = groupTasks.filter(function(e) {
return e.indexOf(key) >= 0;
})[0]
if (!group) {
group = [key];
groupTasks.push(group);
}
for (var dependKey in map[key]) {
if (group.indexOf(dependKey) == -1) {
group.push(dependKey);
}
}
}
var result = groupTasks.map(function(group) {
var tasks = [];
group.forEach(function(id) {
var task = inputArr.filter(function(e) { return e.id == id })[0];
tasks.push(task);
});
return tasks;
})
console.log(JSON.stringify(result, null, 4));
I am trying to search for an object in an array of objects.
Note, vals and recs objects will be DYNAMIC.
var vals = {ID: "4", LOC: "LA", SEQ: "1"};
var recs = [
{ID:"4", LOC:"LA", SEQ:"1"},
{ID:"4", LOC:"NY", SEQ:"1"},
{ID:"4", LOC:"CHI",SEQ:"1"}
];
Now I need to check if all key:value pairs in vals already exist in recs . In this case, recs[0] is an exact match of vals.
Heres my attempt:
var vals = {ID: "4", LOC: "LA", SEQ: "1"};
var recs = [
{ID:"4", LOC:"LA", SEQ:"1"},
{ID:"3", LOC:"NY", SEQ:"2"},
{ID:"2", LOC:"CHI",SEQ:"3"}
];
for(var i = 0; i<recs.length; i++){
if(recs[i]["ID"] == vals["ID"] && recs[i]["LOC"] == vals["LOC"] && recs[i]["SEQ"] == vals["SEQ"]){
console.log(true);
}
else{
console.log(false);
}
}
The above works only because I have hardcoded the keys from the vals object. In reality, the VALS object (and recs) will be DYNAMIC with X number of key:value pairs.
So how can I modify my for loop for a dynamic vals object?
thanks!
Try this:
for (var i = 0; i < recs.length; i++) {
var found = true;
for (var p in vals) {
if (vals.hasOwnProperty(p)) {
if (recs[i][p] !== vals[p]) {
found = false;
break;
}
}
}
console.log(found);
}
for(var i = 0; i<recs.length; i++) {
for (var prop in object) {
if (recs[i][prop] != vals[prop]) {
console.log(false);
return;
}
}
//check from both sides
for (var prop in vals) {
if (recs[i][prop] != vals[prop]) {
console.log(false);
return;
}
}
console.log(true);
}
You could iterate over the keys; something along the lines of:
var vals = { ID: "4", LOC: "LA", SEQ: "1", REGION: "USA" };
var recs = [{ ID: 4, LOC: "LA", SEQ: "1", REGION: "USA" },
{ ID: 3, LOC: "NY", SEQ: "2", REGION: "USA" },
{ ID: 2, LOC: "CHI", SEQ: "3", REGION: "USA" }
];
var isSame = true;
for (var i = 0; i < recs.length; i++) {
console.log( i + '----------------' );
var isSame = true;
// get the keys of the record
var keys = Object.keys(recs[i]);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
var record = recs[i]
console.log( key + ": " + record[key] + '=' + vals[key] );
if (record[key] != vals[key] ) {
isSame = false;// not equal
break;
}
}
console.log('isSame: ' + isSame );
console.log('------------------' );
}
You need to break it into two loops, one for each object of the array and one for each key of the object:
for(var i = 0; i<recs.length; i++){
var found = false
for(var key in recs[i]) {
if(recs[i].hasOwnProperty(key)){
if(recs[i][key] != vals[key]){
found = true
}
}
console.log(found)
}
the hasOwnProperty call will make sure it doesn't break if the object does not have that key.
You can try this:
function myFind(recs, vals) {
return recs.some(function(obj) {
for (var x in obj)
if (x in vals && obj[x] != vals[x])
return false;
return true;
});
}
var recs = [
{ID:4, LOC:"LA", SEQ:"1", USA:"USA"},
{ID:3, LOC:"NY", SEQ:"2", USA:"USA"},
{ID:2, LOC:"CHI",SEQ:"3", USA:"USA"}
];
var vals = {ID: "4", LOC: "LA", SEQ: "1"};
if (myFind(recs, vals)) {
alert('found');
} else {
alert('not found');
}
Hope it helps.
you can use underscorejs isEqual for this kind of problem
I want to merge arrays a little bit different way.
I have 2 or more arrays like:
var array1 = ["apple", "banana"];
var array2 = ["apple", "apple", "orange"];
I want the output:
var array3 = ["apple", "apple", "banana", "orange"];
So if any given array has a variable in it more than once, merge algorithm should keep all of them from that array.
I saw some code that prevents duplication but it gives outputs like this:
var array3 = ["apple", "banana", "orange"];
for more example:
var arr1 = [1,2,3,4];
var arr2 = [1,1,2,4,5,5,5];
var arr3 = [1,3,3,5,5];
I want the output:
var array4 = [1,1,2,3,3,4,5,5,5];
How can I do this?
Here's one way to do it by counting the occurrences of each item in each array:
var arr1 = [1,2,3,4];
var arr2 = [1,1,2,4,5,5,5];
var arr3 = [1,3,3,5,5];
function joinCommon(/* list of arrays */) {
var arr, arrayCounts, masterList = {}, item, output;
// for each array passed in
for (var i = 0; i < arguments.length; i++) {
arr = arguments[i];
arrayCounts = {};
// iterate each array
for (var j = 0; j < arr.length; j++) {
item = arr[j];
if (!arrayCounts[item]) {
arrayCounts[item] = 1;
} else {
++arrayCounts[item];
}
// now keep master list and master counts
if (!masterList[item]) {
masterList[item] = {cnt: 1, val: item};
} else {
masterList[item].cnt = Math.max(masterList[item].cnt, arrayCounts[item]);
}
}
}
// now output result
output = [];
for (var i in masterList) {
for (var j = 0; j < masterList[i].cnt; j++) {
output.push(masterList[i].val);
}
}
return output;
}
var results = joinCommon(arr1, arr2, arr3);
Working demo: http://jsfiddle.net/jfriend00/dtn6zw4m/
Here is a solution using ECMA5.
Javascript
function indexOf(items, value) {
return items.map(function (subitem) {
return subitem.value;
}).indexOf(value);
}
function countItems(previous, item) {
var atIndex = indexOf(previous, item);
if (atIndex !== -1) {
previous[atIndex].count += 1;
} else {
previous.push({
value: item,
count: 1
});
}
return previous;
}
function mergeCounts(item) {
var atIndex = indexOf(this, item.value);
if (atIndex === -1) {
this.push(item);
} else if (this[atIndex].count < item.count) {
this[atIndex] = item;
}
}
function expandCounts(previous, item) {
var iter;
for (iter = 0; iter < item.count; iter += 1) {
previous.push(item.value);
}
return previous;
}
function mergeArg(items, arg) {
arg.reduce(countItems, []).forEach(mergeCounts, items);
return items;
}
function mergeMaxItems() {
return [].reduce.call(arguments, mergeArg, []).reduce(expandCounts, []);
}
var arr1 = [1, 2, 3, 4],
arr2 = [1, 1, 2, 4, 5, 5, 5],
arr3 = [1, 3, 3, 5, 5];
document.body.appendChild(document.createTextNode(mergeMaxItems(arr1, arr2, arr3)));
I like to use ramda (http://ramdajs.com/docs/index.html) for this stuff
var arr1 = [1,2,3,4];
var arr2 = [1,1,2,4,5,5,5];
var arr3 = [1,3,3,5,5];
var allArrays = [arr1, arr2, arr3];
var allValues = R.compose(R.uniq, R.flatten)(allArrays);
var getItemCounts = R.countBy(function(item) {
return item;
});
var itemCounts = R.map(function(arr) {
return getItemCounts(arr);
})(allArrays);
var combined = [];
R.forEach(function(item) {
var countsForItem = R.pluck(item, itemCounts);
var maxCount = R.max(countsForItem);
combined.push.apply(combined, R.repeatN(item, maxCount));
})(allValues);
console.log(combined.sort());
JSFiddle: http://jsfiddle.net/pcr0q1xa/3/
Ramda is your friend.
function merge () {
return R.chain(R.apply(R.repeat), R.toPairs(R.reduce(
R.mergeWith(R.max),
{},
R.map(R.countBy(R.identity), arguments)
)))
}
var array1 = ["apple", "banana"];
var array2 = ["apple", "apple", "orange"];
console.log(JSON.stringify(merge(array1, array2)))
var arr1 = [1,2,3,4];
var arr2 = [1,1,2,4,5,5,5];
var arr3 = [1,3,3,5,5];
console.log(JSON.stringify(merge(arr1, arr2, arr3)))
<script src="http://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script>
Untested and not JS, but I think this is what you are looking for.
I have just tested it manually, it worked for your test cases.
while items in lista or items in listb
compare a.head, b.head
if a.head is smaller or b.is_empty then
append a.head to output
a.drophead
else if b.head is smaller or a.is_empty then
append b.head to output
b.drophead
else
append b.head to output
b.drophead
a.drophead
I know given a single key (for example, if I know the object.name = 'Sam') using:
var index = array.map(function(el) {return el.name}).indexOf('Sam');
I can get the index of the array element with object.name = 'Sam'
However say I have several elements with object.name ='Sam' in the array, but now I know know the object.name, object.age and object.size - is it possible to adapt the above code to get the index but also checking against object.age and object.size?
Assuming you have the values in variables such as name, age and size as you mentioned in comments, You can use a function like:
function findInArray(arr) {
for (var i = 0; i < arr.length; i++) {
var el = arr[i];
if (el.name == name && el.age == age && el.size == size)
return i;
}
return -1;
};
Which will return the index of object in array if match is found, and -1 otherwise...
var data = [{
name: "Sis",
age: "17",
size: "10"
}, {
name: "Sam",
age: "17",
size: "10"
}, {
name: "Som",
age: "17",
size: "10"
}],
name = "Sam",
age = "17",
size = "10";
function findInArray(arr) {
for (var i = 0; i < arr.length; i++) {
var el = arr[i];
if (el.name == name && el.age == age && el.size == size)
return i;
}
return -1;
};
console.log(findInArray(data));
If you're using the awesome underscore library there's a _.findWhere function.
var sam21 = _.findWhere(people, {
name: 'Sam',
age: 21
});
if you want something without a whole other library you can use .filter.
var sam21 = people.filter(function(person) {
return person.age === 21 && person.name === 'Sam';
});
I just noticed you're looking for the index. This answer can be useful: https://stackoverflow.com/a/12356923/191226
You could use a function like this one
indexOfObjectArray = function(array, keyvalues) {
for (var i = 0; i < array.length; i++) {
var trueCount = 0;
for (var j = 0; j < keyvalues.length; j++) {
if (array[i][keyvalues[j]['key']] == keyvalues[j]['value']) {
trueCount++;
}
}
if (trueCount === keyvalues.length) return i;
}
return -1; }
and use it like that for example:
var yourArray = [{id: 10, group: 20},...];
var keyvalues = [
{ 'key': 'id', 'value': 10 },
{ 'key': 'group', 'value': 20 }];
var index = indexOfObjectArray(yourArray, keyvalues );
This function will return the index of an object that has id = 10 and group = 20