Given two Arrays - contacts() & contactsSelected() - How to match the two? - javascript

I have two arrays (contacts & contactsSelected) both with the following type of structure:
{
id: 1,
name: bob
},
{
id: 213,
name: Rob
}
I'm using KnockoutJS. How Can I iterate over contacts() and for each row, determine if that row's ID is contained in the contactsSelected array? In KnockoutJS I have something like this:
userCardModel.contactsToShow = ko.dependentObservable(function () {
return ko.utils.arrayFilter(this.contacts(), function(contact) {
return /////////////// LOGIC GOES HERE TO See if this contact.id() is contained in the contactsSelected() array
});
}, userCardModel);
Thanks

OK, you could do it like so...
var contactsSelectedLength = contacts.length;
for (var i = 0, contactsLength = contacts.length; i++) {
var contact = contacts[i];
for (var j = 0; j < contactsSelectedLength; j++) {
var selectedContact = contactsSelected[j];
if (contact.id == selectedContact.id) {
// It is in there!
}
}
}

Add the IDs of "contactsSelected" as properties of an object so they can be accessed in better-than-linear time using the "in" operator or "hasOwnProperty" method:
var getSelectedIds = function(sel) {
var len=sel.length, o={}, i;
for (i=0; i<len; i++) {
o[sel[i].id] = true;
}
return o;
};
var selectedIds = getSelectedIds(contactsSelected);
(1 in selectedIds); // => true
(2 in selectedIds); // => false
selectedIds.hasOwnProperty(213); // => true
selectedIds.hasOwnProperty(214); // => false

Related

convert special array to object [duplicate]

This question already has answers here:
Create objects dynamically out of a dot notation like string
(6 answers)
Closed 1 year ago.
I am trying to convert the following array into an object:
var arr = [
'car.name',
'car.age',
'car.event.id',
'zz.yy.dd.aa',
'aa.yy.zz.dd.kk'
];
So it will look like this:
var targetObject = {
car: {
name: '',
age: '',
event: {
id: ''
}
}
,
zz: {
yy: {
dd: {
aa: ''
}
}
},
aa: {
yy: {
zz: {
dd: {
kk: '',
}
}
}
}
}
This is my code:
targetObject = {}
function arrayToObject(arr){
//iterate through array and split into items
for (var i = 0; i < arr.length; ++i){
var item = arr[i].split(".");
//iterate through item that has just been splitted
for (var u = 0; u < item.length; ++u){
//if item is not in targetobject create new object
if(!(item[0] in targetObject)){
targetObject[item[0]] = {}
} else {
//else go into the object and add the item/property to the existing object
targetObject[item[0]][item[u]] = {}
}
}
}
console.log(targetObject);
}
arrayToObject(arr);
It outputs only in second level and i can't figure out to do it with the several levels. I know the code is oldschool, so I would also really like to know how this can be done easier.
You could use forEach to loop over array and then split with reduce to build nested object.
var arr = [
'car.name',
'car.age',
'car.event.id',
'zz.yy.dd.aa',
'aa.yy.zz.dd.kk'
];
const result = {}
arr.forEach(str => {
str.split('.').reduce((r, e, i, a) => {
return r[e] = (r[e] || (a[i + 1] ? {} : ''))
}, result)
})
console.log(result)
Or with your approach with for loops you just need to keep some reference and update the current nested object, so you could do it like this.
var arr = [
'car.name',
'car.age',
'car.event.id',
'zz.yy.dd.aa',
'aa.yy.zz.dd.kk'
];
const targetObject = {}
let ref = targetObject;
function arrayToObject(arr) {
//iterate through array and split into items
for (var i = 0; i < arr.length; ++i) {
var item = arr[i].split(".");
//iterate through item that has just been splitted
for (var u = 0; u < item.length; ++u) {
const last = u == item.length - 1
const str = item[u]
if (!ref[str]) {
ref[str] = (last ? '' : {})
}
ref = ref[str]
if (last) {
ref = targetObject;
}
}
}
}
arrayToObject(arr);
console.log(targetObject)

Compare two arrays with objects and show which item is deleted

I have two arrays which I want to compare and check if there is an deleted item in one of these arrays. If there is show me the difference (deleted item)
Here is the code below how I would like to achieve this:
function compareFilters (a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
console.log('k', k);
diff.push(k);
}
return diff;
}
console.log(filters);
console.log(filters, queryBuilderFilters, compareFilters(queryBuilderFilters, filters));
This will log both arrays which look like this:
[
0: {
id: "AggregatedFields.ReturnOnAdSpend",
label: "ROAS (Return on Ad Spend)",
type: "integer",
description: "The ROAS (Return on Ad Spend)."
},
1: {
id: "AggregatedFields.ROIExcludingAssisted",
label: "ROI excl. assisted",
type: "integer",
description: "The ROI excluding any assisted values.
}
]
And the output of the compareFilters function is 0: "[object Object]"
How can I return the label of the object in this function?
This example illustrates what you want
var completedList = [1,2,3,4,7,8];
var invalidList = new Set([3,4,5,6]);
// filter the items from the invalid list, out of the complete list
var validList = completedList.filter((item) => {
return !invalidList.has(item);
})
console.log(validList); // Print [1,2,7,8]
// get a Set of the distinct, valid items
var validItems = new Set(validList);
You can try this, supposing that the objects in each array have the same reference and are not copies:
function compareFilters (a1, a2) {
const a1l = a1.length;
const a2l = a2.length;
// Both arrays are considered to be equal
if(a1l === a2l) return;
let completed;
let unCompleted;
let deletedValue;
if(a1l > a2l) {
completed = a1;
unCompleted = a2;
} else {
completed = a2;
unCompleted = a1;
}
for(let i = 0; i < completed.lenth; i++) {
if(completed[i] !== unCompleted[i]) {
return completed[i].label;
}
}
}
It will return undefined in case both arrays has the same quantity of elements. Otherwise, it will return the label of first element that is in one array but not the another.

How to Splice in a javascript array based on property?

I am getting an array of data in Angularjs Grid and I need to delete all the rows which has same CustCountry
ex - My Customer Array looks like
Customer[0]={ CustId:101 ,CustName:"John",CustCountry:"NewZealand" };
Customer[1]={ CustId:102 ,CustName:"Mike",CustCountry:"Australia" };
Customer[2]={ CustId:103 ,CustName:"Dunk",CustCountry:"NewZealand" };
Customer[3]={ CustId:104 ,CustName:"Alan",CustCountry:"NewZealand" };
So , in the Grid I need to delete all three records if CustomerCountry is NewZealand
I am using splice method and let me know how can I use by splicing through CustomerCountry
$scope.remove=function(CustCountry)
{
$scope.Customer.splice(index,1);
}
If you're okay with getting a copy back, this is a perfect use case for .filter:
Customer = [
{ CustId:101 ,CustName:"John",CustCountry:"NewZealand" },
{ CustId:102 ,CustName:"Mike",CustCountry:"Australia" },
{ CustId:103 ,CustName:"Dunk",CustCountry:"NewZealand" },
{ CustId:104 ,CustName:"Alan",CustCountry:"NewZealand" },
]
console.log(Customer.filter(cust => cust.CustCountry !== "NewZealand"));
if you have one specific country in mind then just use .filter()
$scope.Customer = $scope.Customer.filter(obj => obj.CustCountry !== "SpecificCountry")
If you want to delete all objects with duplicate countries then, referring to Remove duplicate values from JS array, this is what you can do:
var removeDuplicateCountries = function(arr){
var dupStore = {};
for (var x= 0; x < arr.length; x++){
if (arr[x].CustCountry in dupStore){
dupStore[arr[x].CustCountry] = false;
} else {
dupStore[arr[x].CustCountry] = true;
}
}
var newarr = [];
for (var x= 0; x < arr.length; x++){
if (dupStore[arr[x].CustCountry]){
newarr.push(arr[x]);
}
}
return arr;
};
$scope.Customer = removeDuplicateCountries($scope.Customer);
Or incorporating the .filter() method
var removeDuplicateCountries = function(arr){
var dupStore = {};
var newarr = arr;
for (var x= 0; x < arr.length; x++){
if (arr[x].CustCountry in dupStore){
newarr = newarr.filter(obj => obj.CustCountry !== arr[x].CustCountry);
} else {
dupStore[arr[x].CustCountry] = true;
}
}
return newarr;
};
$scope.Customer = removeDuplicateCountries($scope.Customer);
if there are many duplicate countries then use the way without .filter()

Add or remove element(s) to array

I have an existing array of objects :
existingArray = [
{object1: 'object1'},
{object2: 'object2'}
{object3: 'object3'},
]
I receive a new one :
newArray = [
{object2: 'object2'},
{object3: 'object3'},
{object4: 'object4'}
]
I want only to modify the existing one to get the new one as the result (push+splice)
Here is what I have for now (is there a better way ?)
for (var i = 0; i < newArray.length; i++) {
// loop first to push new elements
var responseToTxt = JSON.stringify(newArray[i]);
var newStatement = false;
for(var j = 0; j < existingArray.length; j++){
var statementToTxt = JSON.stringify(existingArray[j]);
if(statementToTxt === responseToTxt && !newStatement){
newStatement = true;
}
}
if(!newStatement){
statements.push(response[i]);
}
}
var statementsToSplice = [];
for (var i = 0; i < existingArray.length; i++) {
// then loop a second time to split elements not anymore on the new array
var statementToTxt = JSON.stringify(existingArray[i]);
var elementPresent = false;
var element = false;
for(var j = 0; j < newArray.length; j++){
var responseToTxt = JSON.stringify(newArray[j]);
if(responseToTxt === statementToTxt && !elementPresent){
elementPresent = true;
} else {
element = i;
}
}
if(!elementPresent){
statementsToSplice.push(element);
}
}
Then I needed to split multiple times in the array :
existingArray = statementsToSplice.reduceRight(function (arr, it) {
arr.splice(it, 1);
return arr;
}, existingArray.sort(function (a, b) { return b - a }));
Here is the example :
https://jsfiddle.net/docmz22b/
So the final output should always be the new array, but only by push or splice the old one.
In this case, the final outpout will be
existingArray = [
{object2: 'object2'},
{object3: 'object3'}
{object4: 'object4'},
]
The new array could contains multiple new elements and/or deleted elements that is currently in the existingArray
Use shift() and push()
existingArray.shift(); //Removes the first element of the array
existingArray.push({'object4' : 'object4'});
Fiddle
I'm almost 100% sure that there is a better way to do it, but at least this works, feel free to comment any suggestions / optimizations.
existingArray = [
{object1: 'object1'},
{object2: 'object2'},
{object3: 'object3'}
];
newArray = [
{object2: 'object2'},
{object3: 'object3'},
{object4: 'object4'}
];
// Loop all the old values, if is not in the new array, remove it
existingArray.forEach(function(item) {
if(!inArray(item, newArray)) {
var idx = indexOfObjectInArray(item, existingArray);
existingArray.splice(idx, 1);
}
});
// Loop all the new values, if is not in the new array, push it
newArray.forEach(function(item) {
if (!inArray(item, existingArray)) {
existingArray.push(item);
}
});
// Auxiliar functions
function inArray(initialValue, array) {
testValue = JSON.stringify(initialValue);
return array.some(function(item) {
return testValue == JSON.stringify(item);
});
}
function indexOfObjectInArray(initialValue, array) {
var result = -1;
testValue = JSON.stringify(initialValue);
array.forEach(function(item, idx) {
if (testValue == JSON.stringify(item)) {
result = idx;
};
});
return result;
}
Maybe this helps. It features Array.prototype.forEach and Array.prototype.some.
Splice unwanted items
Look if object with same property exist
If yes, then assign new object
Else push the object
var existingArray = [
{ object1: 'object1' },
{ object2: 'object2' },
{ object3: 'object3' },
],
newArray = [
{ object2: 'object22' },
{ object3: 'object33' },
{ object4: 'object44' }
];
function update(base, change) {
var changeKeys = change.map(function (a) { return Object.keys(a)[0]; }),
i = 0;
while (i < base.length) {
if (!~changeKeys.indexOf(Object.keys(base[i])[0])) {
base.splice(i, 1);
continue;
}
i++;
}
change.forEach(function (a) {
var aKey = Object.keys(a)[0];
!base.some(function (b, i, bb) {
if (aKey === Object.keys(b)[0]) {
bb[i] = a; // if that does not work, use bb.splice(i, 1, a);
return true;
}
}) && base.push(a);
});
}
update(existingArray, newArray);
document.write('<pre>' + JSON.stringify(existingArray, 0, 4) + '</pre>');

How can I find which index in an array contains an object whose value for a specific key is x? [duplicate]

I would like to find index in array. Positions in array are objects, and I want to filter on their properties. I know which keys I want to filter and their values. Problem is to get index of array which meets the criteria.
For now I made code to filter data and gives me back object data, but not index of array.
var data = [
{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
},
{
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}
];
var filterparams = {userid:'7', chid: 'default'};
function getIndexOfArray(thelist, props){
var pnames = _.keys(props)
return _.find(thelist, function(obj){
return _.all(pnames, function(pname){return obj[pname] == props[pname]})
})};
var check = getIndexOfArray(data, filterparams ); // Want to get '2', not key => val
Using Lo-Dash in place of underscore you can do it pretty easily with _.findIndex().
var index = _.findIndex(array, { userid: '7', chid: 'default' })
here is thefiddle hope it helps you
for(var intIndex=0;intIndex < data.length; intIndex++){
eachobj = data[intIndex];
var flag = true;
for (var k in filterparams) {
if (eachobj.hasOwnProperty(k)) {
if(eachobj[k].toString() != filterparams[k].toString()){
flag = false;
}
}
}
if(flag){
alert(intIndex);
}
}
I'm not sure, but I think that this is what you need:
var data = [{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
}, {
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}];
var filterparams = {userid:'7', chid: 'default'};
var index = data.indexOf( _.findWhere( data, filterparams ) );
I don't think you need underscore for that just regular ole js - hope this is what you are looking for
var data = [
{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
},
{
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}
];
var userid = "userid"
var filterparams = {userid:'7', chid: 'default'};
var index;
for (i=0; i < data.length; i++) {
for (prop in data[i]) {
if ((prop === userid) && (data[i]['userid'] === filterparams.userid)) {
index = i
}
}
}
alert(index);

Categories

Resources