Checking Each Value in For Loop - javascript

I've searched for an answer for this but haven't found one that cover this well with a good example.
I have a for loop:
for (var i=0;i<userProfileProperties.length;i++) {
if (userProfileProperties[i].indexOf("ValueImSearchingFor") {
console.log("GOTIT");
}
}
I'm trying to test each value in the loop to see if it contains a certain set of letters. If it doesn't, that value can be dropped. I can't get this to work. I've searched and have found examples but none seem do what I'm trying to do. or at least I've found no "working" example. I'm new to javascript.
So if my values in the loop returned normally would be: Jack User1, Jill User1, and Jerry User2; the values I want returned are all "User1"
I can't get this to work for:
while(userEnumerator.moveNext()){
var oUser = userEnumerator.get_current();
if(oUser.val.indexOf('ValueImsearchingFor') > -1)
{ ... do this} }

Use Array.prototype.filter() method available for arrays as below:
ES5
var res = userProfileProperties.filter(function (val) {
return val.indexOf("ValueImSearchingFor") > -1
});
ES6
let res = userProfileProperties.filter((val) => {
return val.indexOf("ValueImSearchingFor") > -1
});
let userProfileProperties = [
'ValueImSearchingFor 1',
'ValueImSearchingFor 2',
'test',
'ValueImSearchingFor 3',
'test 1'
];
let res = userProfileProperties.filter((val) => {
return val.indexOf("ValueImSearchingFor") > -1
});
console.log(res);

Related

How to get specific data in JSON result

Here my JSON result of my "modeles" of car:
[
{
"idModele":1,
"modele":"M3",
"marque":{
"idMarque":1,
"marque":"BMW"
}
},
{
"idModele":2,
"modele":"RS6",
"marque":{
"idMarque":2,
"marque":"Audi"
}
},
{
"idModele":3,
"modele":"C63 AMG",
"marque":{
"idMarque":3,
"marque":"Mercedes"
}
},
{
"idModele":4,
"modele":"Clio RS Trophy",
"marque":{
"idMarque":4,
"marque":"Renault"
}
},
{
"idModele":5,
"modele":"Scirocco Type R",
"marque":{
"idMarque":5,
"marque":"Volkswagen"
}
},
{
"idModele":6,
"modele":"118d",
"marque":{
"idMarque":1,
"marque":"BMW"
}
}
]
I just want to get the "modeles" that have the "idMarque:1" (BMW) (in my result they have 2 "modeles") but I don't know how to do it.
My backend : API REST with SpringBoot
My frontend : Angular
Assuming the json array is stored in the variable result, you may simply:
Loop over the json-array.
Check each json-object for the desired condition.
for (let i = 0; i < result.length; i++) {
if (result[i].marque.idMarque === 1) {
console.log('Found it ', result[i]);
}
}
Even simpler:
result.filter(e => e.marque.idMarque === 1);
First, just for clarification, this is a javascript question. It doesn't matter what your backend or frontend is.
Answering your question, you can filter your result to get only the elements you're seeking:
filteredCars = cars.filter(car => car.marque.idMarque === 1)
This will filter the cars with marque.idMarque = 1.
You can find about the filter function on the docs.
You can get the model having idMarque:1 using filter operator. For example you get the JSON result in result class variable. Then you can use filter as follows.
let BMWCars = this.result.filter(e => e.marque.idMarque == 1);
Is a good idea to check, if you have searched object values, so:
let filtered = models
.filter(item => item.marque && item.marque.idMarque
? item.marque.idMarque === 1
: '')
In this case, if you did not get error, when marque key is missing from server response.

JSON Group by Name and then Display Latest Record

Using only JavaScript, I need to
Group by code.
Get latest modifieddate.
Display total grouped code as Count.
Starting JSON Result
[
{"ID":1,"code":"AAA","modifieddate":"2019-06-01","user":"John"},
{"ID":2,"code":"AAA","modifieddate":"2019-06-02","user":"Jane"},
{"ID":3,"code":"AAA","modifieddate":"2019-06-03","user":"Sue"},
{"ID":4,"code":"BBB","modifieddate":"2019-06-10","user":"Rick"},
{"ID":5,"code":"CCC","modifieddate":"2019-06-11","user":"Joe"}
]
Desired JSON Result set
[
{"ID":3,"code":"AAA","modifieddate":"2019-06-03","user":"Sue","Count":"3"},
{"ID":4,"code":"BBB","modifieddate":"2019-06-10","user":"Rick","Count":"1"},
{"ID":5,"code":"CCC","modifieddate":"2019-06-11","user":"Joe","Count":"1"}
]
Tried using reduce method.
I do not have access to modify the server side API code.
I am using Aurelia JS.
You can use Array.reduce to group the result set by each item's code property, incrementing Count as needed, then take the values from the accumulation object. Along the way, we perform a date comparison to determine which the most recent entry to include in the result.
const data = [ {"ID":1,"code":"AAA","modifieddate":"2019-06-01","user":"John"}, {"ID":2,"code":"AAA","modifieddate":"2019-06-02","user":"Jane"}, {"ID":3,"code":"AAA","modifieddate":"2019-06-03","user":"Sue"}, {"ID":4,"code":"BBB","modifieddate":"2019-06-10","user":"Rick"}, {"ID":5,"code":"CCC","modifieddate":"2019-06-11","user":"Joe"} ];
const result = Object.values(data.reduce((a, e) => {
if (!a[e.code]) {
a[e.code] = {...e, Count: 0};
}
if (Date.parse(e.modifieddate) > Date.parse(a[e.code].modifieddate)) {
a[e.code] = {...e, Count: a[e.code].Count};
}
a[e.code].Count++;
return a;
}, {}));
console.log(result);
By the way, this is just a plain JS array we're working with, not JSON.
This should get you:
let array = [
{"ID":1,"code":"AAA","modifieddate":"2019-06-01","user":"John"},
{"ID":2,"code":"AAA","modifieddate":"2019-06-02","user":"Jane"},
{"ID":3,"code":"AAA","modifieddate":"2019-06-03","user":"Sue"},
{"ID":4,"code":"BBB","modifieddate":"2019-06-10","user":"Rick"},
{"ID":5,"code":"CCC","modifieddate":"2019-06-11","user":"Joe"}
]
let result = array.reduce(function(total, currentValue, currentIndex, arr) {
let index = total.findIndex(function(entry) { return entry.code == currentValue.code; })
if (index >= 0) { // entry already exists
// check modified
if (total[index].modifieddate > currentValue.modifieddate) { // already have most recent of the two
total[index].Count += 1;
} else { // need to replace with more recent
currentValue.Count = total[index].Count + 1;
total[index] = currentValue;
}
} else { // first record for this code
currentValue.Count = 1;
total.push(currentValue);
}
return total;
}, []);
console.log(result);
Here is a working js-fiddle
Note: Comments are made in code block

Remove singular element from an object's key array

I have an object that has multiple keys and each of these keys has an array storing multiple elements. I want to be able to remove a specified element from the key's array.
I have tried using the delete keyword as well as the filter method, but I have been unsuccessful. I'm a total newbie to JS so I appreciate any assistance. Also, I want to do this using ONLY JavaScript, no libraries.
Here is the code where I am creating my object:
function add(task, weekdayDue) {
let capitalWeekday = weekdayDue.charAt(0).toUpperCase() +
weekdayDue.slice(1);
if (toDoList[capitalWeekday] === undefined) {
let subArr = [];
toDoList[capitalWeekday] = subArr.concat(task);
} else {
toDoList[capitalWeekday].push(task);
}
}
and here is the code as I have it now. Clearly it is not producing the correct result:
function remove(task, weekdayDue) {
let capitalWeekday = weekdayDue.charAt(0).toUpperCase() +
weekdayDue.slice(1);
delete toDoList.capitalWeekday[task]
//the below code is working; i want to send this to another
array
if (archivedList[capitalWeekday] === undefined) {
let subArr = [];
archivedList[capitalWeekday] = subArr.concat(task);
} else {
archivedList[capitalWeekday].push(task);
}
};
add('laundry', 'monday');
add('wash car', 'monday');
add ('vacuum', 'tuesday');
add('run errands', 'wednesday');
add('grocery shopping', 'wednesday');
// the output is: { Monday: [ 'laundry', 'wash car' ],
Tuesday: [ 'vacuum' ],
Wednesday: [ 'run errands', 'grocery shopping' ] }
Then let's say I want to remove 'wash car' from Monday I was trying:
remove('wash car', 'monday');
console.log(toDoList)
// The output is an empty object {}
I personally would refactor a bit your code, but I've worked a bit around it to fix some issues.
First of all, you shouldn't use delete for your scenario, because it will reset the item at the nth position of the array with the default value, which is undefined.
Usually, for that kind of operations, since you deal with strings, you rather take a look at the first occurrence of your item in the array, take its index, and use splice (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) to actually remove the item from the array.
In this way, you end up with a clean array without invalid items in it.
Below is the working code (with the mentioned fixes) that does what you asked. As a side note, I would suggest you to avoid working with strings for such purposes, but I would rather tackle objects with unique ids, so that it's significantly easier to keep track of them between arrays and objects.
Additionally, there are some cases that you didn't think about, for instance I can think about calling remove by giving an invalid task, so you may work a bit around the code below to handle the case where taskIndex is -1 (meaning that no item was found with that index).
var toDoList = {}, archivedList = {};
function add(task, weekdayDue) {
let capitalWeekday = weekdayDue.charAt(0).toUpperCase() + weekdayDue.slice(1);
if (toDoList[capitalWeekday] === undefined) {
let subArr = [];
toDoList[capitalWeekday] = subArr.concat(task);
} else {
toDoList[capitalWeekday].push(task);
}
}
function remove(task, weekdayDue) {
let capitalWeekday = weekdayDue.charAt(0).toUpperCase() + weekdayDue.slice(1);
let taskIndex = toDoList[capitalWeekday].indexOf(task);
toDoList[capitalWeekday].splice(taskIndex, 1);
//delete toDoList[capitalWeekday][taskIndex];
if (archivedList[capitalWeekday] === undefined) {
let subArr = [];
archivedList[capitalWeekday] = subArr.concat(task);
} else {
archivedList[capitalWeekday].push(task);
}
};
add('test', 'monday');
add('wash car', 'monday');
remove('wash car', 'monday');
console.log(toDoList);
console.log(archivedList);
You are on the right path. Maybe the trouble you had with filter is because filter will return a new Array and not modify the current one. You could update your remove function and replace the line:
delete toDoList.capitalWeekday[task]
with
toDoList.capitalWeekday = toDoList.capitalWeekday.filter((item) => {return item !== task});
function remove(task, weekdayDue) {
let capitalWeekday = weekdayDue.charAt(0).toUpperCase() +
weekdayDue.slice(1);
// Assign new array with all elements but task
toDoList[capitalWeekday] = toDoList[capitalWeekday].filter(i => i !== task)
};
add('foo'...
add('bar'...
"{
"Baz": [
"Foo",
"Bar"
]
}"
remove('foo'...
"{
"Baz": [
"Bar"
]
}"

Filter/de-duplicate repeated variables

I am trying to add functionality into my JS script that de-duplicates the values returned. My original script here:
try{
var productList = dataLayer.basket.products.map(function(product) {
return product.travelType;
});
return productList.join('|');
}
catch(err){}
which returns values from an array like Bus|Bus|Train|Car|Bus
What I am trying to get to is an additional part of the script that would clean those values and de-duplicate them. For example the above script would only show "bus" once e.g. Bus|Train|Car
I have tried to do this using a filter but I am getting a null value being returned:
try{
var productList = dataLayer.basket.products.map(function(product) {
return product.travelType;
});
var filteredArray = productList.filter(function(item, pos){
return productList.indexOf(item)=== pos;
});
return filteredArray.join('|');
}
catch(err){}
Any guidance would be gratefully appreciated.
Thanks,
M
To filter duplicates in an array:
const array = ['toto', 'tata', 'tutu', 'toto'];
const filteredArray = [...new Set(array)];
console.log(filteredArray);
const remove_duplicates = (arr) => {
let setArr = new Set(arr);
let values = setArr.values();
return Array.from(values);
}
const example = ['Bus', 'Bus', 'Car', 'Bike'];
console.log(remove_duplicates(example).join('|'));
Your code is fine as is, the error must be in your data or in another part of your code that you didn't post:
const dataLayer = {
basket:{products:[
{travelType:'a'},
{travelType:'b'},
{travelType:'c'},
{travelType:'b'},
{travelType:'c'},
{travelType:'a'},
]}
}
var productList = dataLayer.basket.products.map(function(product) {
return product.travelType;
});
var filteredArray = productList.filter(function(item, pos){
return productList.indexOf(item)=== pos;
});
console.log(filteredArray.join('|'));
Using modern javascript:
let arr = ['Bus', 'Bus', 'Train', 'Car', 'Bus'];
let filteredArr= [... new Set(arr)];
let result = filteredArr.join('|');
I think the top answer in this question is just what you're searching for. Just apply that to your productList and it should get rid of all duplicate values.
Edit: oops, I just saw you were already doing exaclty that. But your code should work that way, I just tried it out in the console and it worked just as expected. The null values must be caused by some other part of your program.

Client-side full-text search on array of objects

I have the following example JavaScript array of objects and need to enable users to search on it using words/phrases, returning the objects:
var items = [];
var obj = {
index: 1,
content: "This is a sample text to search."
};
items.push(obj);
obj = {
index: 2,
content: "Here's another sample text to search."
};
items.push(obj);
It's probably efficient to use jQuery's $.grep to perform the search, such as this for a single word:
var keyword = "Here";
var results = $.grep(items, function (e) {
return e.content.indexOf(keyword) != -1;
});
However, how do you search for a phrase in the content field of the objects? For example, searching for the phrase another text won't work using indexOf, because the two words aren't next to each other. What's an efficient way to perform this search in jQuery?
You can use vanilla JS if you're stuck. It does use filter and every which won't work in older browsers, but there are polyfills available.
var items = [];
var obj = {
index: 1,
content: "This is a sample text to search."
};
items.push(obj);
obj = {
index: 2,
content: "Here's another sample text to search."
};
items.push(obj);
function find(items, text) {
text = text.split(' ');
return items.filter(item => {
return text.every(el => {
return item.content.includes(el);
});
});
}
console.log(find(items, 'text')) // both objects
console.log(find(items, 'another')) // object 2
console.log(find(items, 'another text')) // object 2
console.log(find(items, 'is text')) // object 1
(Edit: updated to use includes, and a slightly shorter arrow function syntax).
if you use query-js you can do this like so
var words = phrase.split(' ');
items.where(function(e){
return words.aggregate(function(state, w){
return state && e.content.indexOf(w) >= 0;
});
},true);
if it should just match at least one change the && to || and true to false

Categories