Anyone know a good way to turn this?:
var obj = [{key1: value1,key2: value2},{key3: value3,key4: value4}];
into:
var obj = [{Key1: value1,Key2: value2},{Key3: value3,Key4: value4}];
Loop through delete and replace:
var obj = [{key1: 1,key2: 1},{key3: 1,key4: 1}];
for(var i = 0; i<obj.length;i++) {
var a = obj[i];
for (var key in a) {
if (a.hasOwnProperty(key)) {
a[key.charAt(0).toUpperCase() + key.substring(1)] = a[key];
delete a[key];
}
}
obj[i] = a;
}
As of 2019 you can use Object.fromEntries:
let populations = {london: 8.9, beijing: 21.54, mumbai: 18.41}; // March 2020
let entries = Object.entries(populations);
let capsEntries = entries.map((entry) => [entry[0][0].toUpperCase() + entry[0].slice(1), entry[1]]);
let capsPopulations = Object.fromEntries(capsEntries);
console.log(capsPopulations);
Another approach (more clean)
import * as _ from 'lodash';
function capitalizeObjectKeys(obj) {
return _.transform(obj, (result, val, key) => {
result[key.charAt(0).toUpperCase() + key.slice(1)] = val;
});
}
https://stackblitz.com/edit/js-hsqutg?embed=1&file=index.js
In my case this code worked well. Both in uppercase and lowercase with map:
to uppercase :
const newDataUpperCase = data.map( function( item ){
for(var key in item){
var upper = key.toUpperCase();
if( upper !== key ){
item[ upper ] = item;
delete item[key];
}
}
return item;
});
to lowercase :
const newDataUpperCase = data.map( function( item ){
for(var key in item){
var lower= key.toLowerCase();
if( lower!== key ){
item[ lower] = item;
delete item[key];
}
}
return item;
});
const transform = (arrObj) => {
let newObj=[];
for(let obj of arrObj) {
let temp=new Object();
let keys = Object.keys(obj);
let values = Object.values(obj);
let i=0;
keys.forEach(key => {
key=key[0].toUpperCase() + key.slice(1);
temp[`${key}`]=values[i++];
});
newObj.push(temp);
}
return newObj;
};
const arrObj = [{first: 'satya', last:'prakash'}, {college: 'AIT'}];
console.log(transform(arrObj));
If you need to capitalize just first letter you can go with Jeremiah's answer
or if you need to capitalize first letter of each word consider the following
let populations = {"london": 8.9, "beijing": 21.54, "mumbai": 18.41, "new york": 19.4};
let entries = Object.entries(populations);
// Capitalize first letter of each word
let capsEntries = entries.map((entry) => [entry[0].replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase()), entry[1]]);
let capsPopulations = Object.fromEntries(capsEntries);
console.log(capsPopulations)
Regex adopted from this answer
Regex Explanation:
(^\w{1}): match first char of string
|: or
(\s{1}\w{1}): match one char that came after one space
g: match all
match => match.toUpperCase(): replace with can take function, so; replace match with upper case match
This will help you:
const griddata = [
{
"id_pk": 238,
"acT_ID": 238,
"desc": "Record 2",
"parent": 0,
"compdays": 5,
"logical": "1",
"quantity": "1",
"lisT_ID": 75,
"empL_ID": 1388,
"default": 8,
"level": "0",
"sortorder": 2,
"vfpRecNo": 0,
"isDeleted": false,
"clientID": 1,
"empl_num": "1388",
"duedate": "05/04/2022"
}
]
const upperCaseKeys = (data) => {
debugger;
let gridData = [];
if (data != null && data != undefined && data.length > 0) {
let keys = Object.keys(data[0]);
let upperCaseKey = [];
for (let j = 0; j < data.length; j++) {
upperCaseKey = [];
for (let i = 0; i < keys.length; i++) {
set(upperCaseKey, keys[i].toUpperCase(), data[j][keys[i]]);
}
upperCaseKey.push(...upperCaseKey);
gridData.push(Object.assign({}, upperCaseKey));
}
}
console.log("upperCaseKeys",gridData)
}
const set = (obj, prop, value) => {
obj[prop] = value;
}
upperCaseKeys(griddata)
Output:
upperCaseKeys [
{
ID_PK: 238,
ACT_ID: 238,
DESC: 'Record 2',
PARENT: 0,
COMPDAYS: 5,
LOGICAL: '1',
QUANTITY: '1',
LIST_ID: 75,
EMPL_ID: 1388,
DEFAULT: 8,
LEVEL: '0',
SORTORDER: 2,
VFPRECNO: 0,
ISDELETED: false,
CLIENTID: 1,
EMPL_NUM: '1388',
DUEDATE: '05/04/2022'
}
]
use lodash's _.capitalize function
_.capitalize('firstName') => FirstName
Related
I am trying to find the places of each letter in a sentence by using "dictionaries". The problem is I want to find all the places that each letter is and not only the last one. I am very new to JavaScript and couldn't figure out the way to do it.
function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g,'');
var dict = {};
for (var i=0; i < stringArgument.length; i++ )
if (!stringArgument[i] in dict){
dict[stringArgument[i]] = [];
}else{
dict[stringArgument[i]] = [i+1]
}
return dict
}
var a = letters('Lost time is never found again.');
console.log(a);
naturally gives this output:
{ L: [ 1 ], o: [ 17 ], s: [ 10 ], t: [ 5 ]...
but it should give this:
{ L: [ 1 ], o: [ 2, 17 ], s: [ 3, 10 ], t: [ 4, 5 ]...
Also each letter is saved to the dictionary at the same order they appear in the sentence, how can I order the letters alphabetically?
What you need is a function that gets the positions of a character in a given string.
Try this:
function findAllPositions(char, content) {
var result = [];
let index = content.indexOf(char);
while(index !== -1) {
result.push(index);
index = content.indexOf(char, index + 1);
}
return result;
}
findAllPositions('o', 'Lost time is never found again.'); // Result = Â [1, 20]
Using this we can update the letter function as follows:
function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g, '');
var dict = {};
for (const char of stringArgument) {
dict[char] = findAllPositions(char, stringArgument)
}
return dict;
}
letters('is again.')
/*
{
"i": [0, 5],
"s": [1],
"a": [2, 4],
"g": [3],
"n": [6],
".": [7]
}
*/
You need to have
parantheses for the check
if (!(stringArgument[i] in dict)) {
create an array if the above is true
push the postion to the array
For getting a sorted output, you could take the entries of the object, apply a sorting by taking the key and show the result in order.
Object have an insertation oder for not positive 32 bit numbers (like indixes) or symbols. The index like numbers are sorted by value and appears first in the object.
function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g, '');
var dict = {};
for (var i = 0; i < stringArgument.length; i++) {
if (!(stringArgument[i] in dict)) {
dict[stringArgument[i]] = [];
}
dict[stringArgument[i]].push(i + 1);
}
return dict;
}
var a = letters('Lost time is never found again.');
Object
.entries(a)
.sort(([a], [b]) => a.localeCompare(b))
.forEach(([key, positions]) => console.log(key, ...positions));
console.log(a);
First, for any item, if it is not in an empty array:
var notInDict = !(stringArgument[i] in dict);
If not in dict, then initialize an empty array and push the item in it using
dict[stringArgument[i]].push(i + 1);
Try this.
function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g, "");
var dict = {};
for (var i = 0; i < stringArgument.length; i++) {
var notInDict = !(stringArgument[i] in dict);
if (notInDict) {
dict[stringArgument[i]] = [];
}
dict[stringArgument[i]].push(i + 1);
}
return dict;
}
var a = letters("Lost time is never found again.");
console.log(a);
you are assigning a new array at each iteration
dict[stringArgument[i]] = [i+1]
what you need to do is push the new position to existing array.
dict[stringArgument[i]].push(i+1)
also, remove the else block
function letters(stringArgument) {
stringArgument = stringArgument.toLowerCase().replace(/ /g,'');
var dict = {};
for (var i=0; i < stringArgument.length; i++ ){
if (!dict.hasOwnProperty(stringArgument[i])){
dict[stringArgument[i]] = [];
}
dict[stringArgument[i]].push(i+1);
}
//sorting
var letters = Object.keys(dict); //returns a array
letters.sort();
var sortedDic = {};
for(var i in letters) {
sortedDic[letters[i]] = dict[letters[i]];
}
return sortedDic;
}
var a = letters('Lost time is never found again.');
console.log(a);
for the first part you can also do that:
let sentence = 'Lost time is never found again.'
let tabLetters = [...sentence.replace(/ /g,'')].reduce((a,c,i)=>
{
if (!a[c]) a[c] = [i+1]
else a[c].push(i+1)
return a
},{})
document.write(JSON.stringify(tabLetters))
I count the words in a paragraph by frequency of occurrences now I need to sort them too for example [this : 2, is : 3, it : 1] to [is : 3, this : 2, it : 1]. I divided keys and values into two different arrays then I sorted an array of values now I want to sort an array of keys
console.log('app running');
function getFrequencyOfWord(word : string) {
let counting: any = {};
let wordSplit: any = word.split(' ');
wordSplit.forEach(function (word: any) {
if (counting[word]) {
counting[word]++;
}
else {
counting[word] = 1;
}
})
var arr1 = Object.keys(counting);
var arr2 = arr1.map((suboor)=> {
return counting[suboor];
});
for (var i : number = 0; i < arr2.length; i++) {
for (var j = 0; j < (arr2.length -i -1); j++) {
if (arr2[j] > arr2[j+1]) {
const lesser = arr2[j+1];
arr2[j+1] = arr2[j];
arr2[j] = lesser;
}
}
}
console.log(arr2);
console.log(arr1);
}```
You could try something like the following:
let word = "moo moo moo hello one two three one";
let wordSplit = word.split(' ');
var counting = [];
wordSplit.forEach(function (word) {
if (counting[word]) {
counting[word]++;
}
else {
counting[word] = 1;
}
})
console.log("Counting ...");console.log(counting);
function swap(json){
var ret = {};
for(var key in json){
let element = ret[json[key]] ;
//console.log("element");console.log(element);
if(element == undefined){
ret[json[key]] = element= [];
}
element.push(key);
//console.log("element");console.log(element);
}
return ret;
}
let result = swap(counting);
console.log("RESULT ...");console.log(result);
var finalResult = [];
for(var key in result){
finalResult = finalResult.concat(result[key]);
}
console.log("Final RESULT ...");console.log(finalResult);
Output
Word Count:
[moo: 3, hello: 1, one: 2, two: 1, three: 1]
Result:
{1: Array(3), 2: Array(1), 3: Array(1)}
1: (3) ["hello", "two", "three"]
2: ["one"]
3: ["moo"]
Final Result
0: "hello"
1: "two"
2: "three"
3: "one"
4: "moo"
Fiddle: https://jsfiddle.net/menelaosbgr/xe9u7mqk/33/
Update
The problem is that you actually have a map of object instead of an array. An array of objects would be something like [{is:3},{this:2},{it:1}] . It's not that difficult to do the conversion. However, I think it's better to have objects that are like this {word:X, count:x}. See below:
let word = "this this is is it is";
let wordSplit = word.split(' ');
var counting = [];
wordSplit.forEach(function (word) {
if (counting[word]) {
counting[word]++;
}
else {
counting[word] = 1;
}
})
console.log("Counting ...");console.log(counting);
function swap(json){
var ret = {};
for(var key in json){
let element = ret[json[key]] ;
//console.log("element");console.log(element);
if(element == undefined){
ret[json[key]] = element= [];
}
element.push({count:json[key], word:key});
//console.log("element");console.log(element);
}
return ret;
}
let result = swap(counting);
console.log("RESULT ...");console.log(result);
//Reverse it and make it into objects...
let reversedResult = Object.assign([], result ).reverse();
console.log("RESULT-REVERSED ...");console.log(reversedResult);
//Final Conatenated Array
var concatenatedArray = [];
for(var key in reversedResult){
concatenatedArray = concatenatedArray.concat(reversedResult[key]);
}
console.log("CONCATENATED-ARRAY ...");console.log(concatenatedArray);
Result:
0: {count: 3, word: "is"}
1: {count: 2, word: "this"}
2: {count: 1, word: "it"}
Fiddle: https://jsfiddle.net/menelaosbgr/xe9u7mqk/49/
This is not possible to sort array of keys according to array of values but you can do something to map right key to right value by checking if(arr[key] == arr[value]) and if key and value are equal then you can push that key value pair into new array.
I have seen the questions but none of them helped me.
I have a string like this:
var Lang_Array1 = "HU,blah,blah,blah,EN,blah,blah,blah,blah,DE,blah,blah,blah,RO,blah,blah,blah";
I want that string to be in different arrays based on the separators "HU", "EN", "DE", "RO".
My approach currently is this(Working but not too elegant):
var Lang_Array1 = Lang_Array.split(",");
console.log(typeof(Lang_Array));
console.log(Lang_Array);
var HU_Langs = [];
var EN_Langs = [];
var DE_Langs = [];
var RO_Langs = [];
for(var i = 0; i < Lang_Array1.length;i++){
if(Lang_Array1[i] != "EN"){
if(Lang_Array1[i] != ""){
HU_Langs[i] = Lang_Array1[i];
}
}else{
for(i;i < Lang_Array1.length;i++){
if(Lang_Array1[i] != "DE"){
if(Lang_Array1[i] != ""){
EN_Langs[i] = Lang_Array1[i];
}
}else{
for(i;i < Lang_Array1.length;i++){
if(Lang_Array1[i] != "RO"){
if(Lang_Array1[i] != ""){
DE_Langs[i] = Lang_Array1[i];
}
}else{
for(i;i < Lang_Array1.length;i++){
if(Lang_Array1[i] != ""){
RO_Langs[i] = Lang_Array1[i];
}
}
break;
}
}
break;
}
}
break;
}
}
That way i get what i want but i want to improve it somehow.
The arrays:
HU_Langs =["HU","blah","blah","blah"];
EN_Langs =["EN","blah","blah","blah"];
DE_Langs =["DE","blah","blah","blah"];
etc...
So how can i improve this code without nested for loops?
EDIT: Thank you for all! All the answers are very very good.
My question wasnt clear and detailed enough but i solved it like this with the help of the correct answer.
Here is the function now:
function Get_Language_Object(Lang_Array){
Lang_Array = Lang_Array.replace(/(\r\n|\n|\r)/gm, "");
var langs = ['HU', 'EN', 'DE', 'RO'];
var isLang = str => langs.includes(str);
var { HU: New_HU_Langs, EN: New_EN_Langs, DE: New_DE_Langs, RO: New_RO_Langs } = Lang_Array.split(',')
.reduce((r, str) => {
if(isLang(str)) r.push([]);
r[r.length - 1].push(str);
return r;
}, [])
.reduce((r, [code, ...arr]) => ({ ...r, [code]: arr }), {});
for(var i = 0; i < TAGS.length;i++){
arrLang.HU[TAGS[i]] = New_HU_Langs[i];
arrLang.EN[TAGS[i]] = New_EN_Langs[i];
arrLang.DE[TAGS[i]] = New_DE_Langs[i];
arrLang.RO[TAGS[i]] = New_RO_Langs[i];
}
Set_Actual_Language();
VNotify("Settings Notfy","Lang Set!","success",1500,"success32.png");
}
Split the string by the delimiter (,), reduce the array, and for every language code, add a new sub-array. Push all items to the last sub-array:
var Lang_Array1 = "HU,blah,blah,blah,EN,blah,blah,blah,blah,DE,blah,blah,blah,RO,blah,blah,blah";
var langs = ['HU', 'EN', 'DE', 'RO'];
var isLang = str => langs.includes(str);
var result = Lang_Array1.split(',')
.reduce((r, str) => {
if(isLang(str)) r.push([]);
r[r.length - 1].push(str);
return r;
}, []);
console.log(result);
If you want to split to multiple arrays, reduce the sub-arrays to an object, and use desturcturing to assign them to variables:
var Lang_Array1 = "HU,blah,blah,blah,EN,blah,blah,blah,blah,DE,blah,blah,blah,RO,blah,blah,blah";
var langs = ['HU', 'EN', 'DE', 'RO'];
var isLang = str => langs.includes(str);
var { HU: HU_Langs, EN: EN_Langs, DE: DE_langs, RO: RO_langs } = Lang_Array1.split(',')
.reduce((r, str) => {
if(isLang(str)) r.push([]);
r[r.length - 1].push(str);
return r;
}, [])
.reduce((r, [code, ...arr]) => ({ ...r, [code]: arr }), {});
console.log(HU_Langs, EN_Langs, DE_langs, RO_langs);
You should reduce the list of words after splitting on your delimiter (,). Each time you run into a known key, you alter the key that refers to the current language.
This is the most succinct example:
let arr = "HU,blaf,blaf,blaf,EN,blah,blah,blah,blah,DE,bla,bla,bla,RO,bah,bah,bah"
let keys = [ "DE", "EN", "HU", "RO" ]
let dict = langDict(arr, keys)
console.log(dict)
function langDict(arr, keys) {
let key = null
return arr.split(/,/g).reduce((dict, token) => {
if (Object.keys(dict).length && key == null) {
throw new Error('No language defined yet!')
} else if (keys.includes(token)) {
key = token
} else {
if (dict[key] == null) dict[key] = []
dict[key].push(token)
}
return dict
}, {})
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
As I believe the upper case ISO2 code is the language hint, you could group all results together in a more scalable way.
var Lang_Array1 = "HU,blah,blah,blah,EN,blah,blah,blah,blah,DE,blah,blah,blah,RO,blah,blah,blah";
var Languages = {};
var current = '';
Lang_Array1.split(',').forEach(function (value) {
if (/^[A-Z]{2}$/.test(value))
current = value;
else
Languages[current] = (Languages[current] || []).concat(value);
});
console.log(Languages);
Above snippet would populate the Languages object like this:
{
"HU": [
"blah",
"blah",
"blah"
],
"EN": [
"blah",
"blah",
"blah",
"blah"
],
"DE": [
"blah",
"blah",
"blah"
],
"RO": [
"blah",
"blah",
"blah"
]
}
At this point, all you have to do is to address directly Languages.EN or others, or recreate the original structure via:
var Lang_Array = Object.keys(Languages).reduce(
function (arr, key) {
return arr.concat(key, Languages[key]);
},
[]
);
You could also create arrays with the language starting at index 0, and values following:
var Lang_EN = ['EN'].concat(Languages.EN);
As summary, grouping by keys seem the best way to represent, and manipulate, such flattened structure.
I hope this helped 👋
If the order is constant:
var Lang_Array1 = "HU,blah1,blah2,blah3,EN,blah4,blah5,blah6,blah7,DE,blah8,blah9,blah10,RO,blah11,blah12,blah13";
const arr1 = Lang_Array1.split(/[HU,EN,DE,RO]/g);
let obj = {hu:[],en:[],de:[],ro:[]};
const keys = Object.keys(obj);
let i = 0;
arr1.forEach(el=>{
if(el !== '')
obj[ keys[i] ].push(el);
else
if(obj[ keys[i] ].length > 0)
i++;
});
console.log(obj);
Response:
{hu: Array(3), en: Array(4), de: Array(3), ro: Array(3)}
hu: (3) ["blah1", "blah2", "blah3"]
en: (4) ["blah4", "blah5", "blah6", "blah7"]
de: (3) ["blah8", "blah9", "blah10"]
ro: (3) ["blah11", "blah12", "blah13"]
Temporary array can be used to reference the array to push to :
var Lang_Array = "HU,blah,blah,blah,EN,blah,blah,blah,blah,DE,blah,blah,blah,RO,blah,blah,blah";
var Lang_Array1 = Lang_Array.split(","), HU_Langs = [], EN_Langs = [], DE_Langs = [], RO_Langs = [];
for (var Langs = [], i = 0; i < Lang_Array1.length; i++)
{
var str = Lang_Array1[i];
Langs = { HU: HU_Langs, EN: EN_Langs, DE: DE_Langs, RO: RO_Langs }[str] || Langs;
Langs.push(str);
}
console.log( HU_Langs, EN_Langs, DE_Langs, RO_Langs );
I have an array with below elements. I am trying to create an object from the array
var arr = [
'find({ qty: { $lt: 20 } } )',
'limit(5)',
'skip(0)'
]
Below is my code. where I am getting only values as the output. Any help on this will be helpful
for (var i = 0; i < arr.length; i++) {
var res = arr[i].search(/\(/ig)
if (res!= -1) {
var result = arr[i].split("(");
result = result[1].slice(0, -1))
}
}
Expected Output
{
"action": "find",
"value": "{ qty: { $lt: 20 } }",
"limit": 5,
"skip": 0
}
match is better than split for this kind of stuff
var arr = [
'find({ qty: { $lt: 20 } } )',
'limit(5)',
'skip(0)'
]
var obj = {};
arr.forEach(function(x, n) {
var m = x.match(/(\w+)\(\s*(.+?)\s*\)/);
if(n == 0) {
obj.action = m[1];
obj.value = m[2];
} else
obj[m[1]] = m[2];
});
document.write("<pre>" + JSON.stringify(obj,0,3));
see this fiddle
Just check if element is first in array, if yes, set action and value keys to splitted array, else just assign splitted values to key and value respectively
var arr = [
'find({ qty: { $lt: 20 } } )',
'limit(5)',
'skip(0)'
]
var result = {};
for (var i = 0; i < arr.length; i++) {
var res = arr[i].split("(")
console.log(res)
result[res[0]] = res[1].split(')')[0]
}
document.write(JSON.stringify(result))
I have this data:
var object = [{
"nid": "31",
"0": {
"tid": "20",
"name": "Bench Press",
"objectDate": "2012-02-08",
"goal": "rep",
"result": "55.00",
"comments": "sick!",
"maxload": "250"
},
"1": {
"tid": "22",
"name": "Back Squat",
"objectDate": "2012-02-08",
"goal": "time",
"result": "8.00",
"comments": "i was tired.",
"maxload": "310"
}},
{
"nid": "30",
"0": {
"tid": "19",
"name": "Fran",
"objectDate": "2012-02-07",
"goal": "time",
"result": "5.00",
"comments": null
}}];
and I would like to filter it by name. For instance, if I apply a filter for the name "Fran", I'd like to have something like this:
[0] => Array
(
[tid] => 19
[name] => Fran
[objectDate] => 2012-02-07
[goal] => time
[result] => 5.00
[comments] =>
)
[1] => Array
(
[tid] => 19
[name] => Fran
[objectDate] => 2012-02-08
[goal] => rep
[result] => 55.00
[comments] => woohoo!
)
Is it possible to achieve?
The question is about multidimensional arrays. If you like me missed that here are solutions for normal arrays...
2020
filteredArray = array.filter(item => item.name.indexOf('Fran') > -1);
or
filteredArray = array.filter(function(item)
{
return item.name.indexOf('Fran') > -1);
}
2012 version
var result = [];
for (var i = 0; i < array.length; i++)
{
if (array[i].name === 'Fran')
{
result.push(array[i]);
}
}
There is no function for this in Javascript. You have to write your own function like this.
var arr = [{"nid":"31","0":{"tid":"20","name":"Bench Press","objectDate":"2012-02-08","goal":"rep","result":"55.00","comments":"sick!","maxload":"250"},"1":{"tid":"22","name":"Back Squat","objectDate":"2012-02-08","goal":"time","result":"8.00","comments":"i was tired.","maxload":"310"}},{"nid":"30","0":{"tid":"19","name":"Fran","objectDate":"2012-02-07","goal":"time","result":"5.00","comments":null}}];
function filterByProperty(array, prop, value){
var filtered = [];
for(var i = 0; i < array.length; i++){
var obj = array[i];
for(var key in obj){
if(typeof(obj[key] == "object")){
var item = obj[key];
if(item[prop] == value){
filtered.push(item);
}
}
}
}
return filtered;
}
var byName = filterByProperty(arr, "name", "Fran");
var byGoal = filterByProperty(arr, "goal", "time");
I would create a function for filtering :
function filter(array, key, value){
var i, j, hash = [], item;
for(i = 0, j = array.length; i<j; i++){
item = array[i];
if(typeof item[key] !== "undefined" && item[key] === value){
hash.push(item);
}
}
return hash;
}
A more robust solution might be adding a filter method to the prototype:
`This prototype is provided by the Mozilla foundation and
is distributed under the MIT license.
http://www.ibiblio.org/pub/Linux/LICENSES/mit.license`
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
Then simply call:
function filterName (item, index, array) {
return (item.name === "Fran");
}
var result = object.filter(filterName);
If your object contains 3 fields, say email, firstName, lastName then you use this.
ArrayObject
.filter(em => em.email.indexOf(searchEmail) > -1)
.filter(fn => fn.firstName.indexOf(searchFirstName) > -1)
.filter(ln => ln.lastName.indexOf(searchLastName) > -1)
The big trick is to make a flat array with just the item you want in it.
say you have a 2d array like so:
e = [[1,2],[1,2],[2,3],[4,5],[6,7]]
you make a new array:
var f = []
fill it with just 1 item:
for(var x=0;x<e.length;x++) f[x] = e[x][1]
giving us the likes of:
f = [2,2,3,5,7]
and then....
var g = e.filter( function(elem, pos){ return (f.indexOf(elem[1]) == pos) })
cowabunga!
I try the solution from Diode. I adapt for my case. There are 3 arrays included.
var arr =
[
{
taskTypeGroupId: "EXP.CONT", taskTypeGroupName: "Contradictoire",
taskType:
{
taskTypeId: "DGE-EXPCONT", taskTypeName: "Dégats des eaux contradictoire", defaultDuration: 60, isInProject: false,
dataItems:
{
id: "EXTRAFILLER5", label: "Divers 5"
}
}
},
{
takTypeGroupId: "EXPQUAL", taskTypeGroupName: "Contrôle qualité",
taskType:
{
taskTypeId: "DGE-EXPQUAL", taskTypeName: "Contrôle qualité dégats des eaux", defaultDuration: 60, isInProject: false,
dataItems:
{
id: "EXTRAFILLER5", label: "Divers 5"
}
}
}
];
function filterByProperty(array, prop, value){
var filtered = [];
for(var i = 0; i < array.length; i++){
var array1 = array[i];
for(var key in array1){
if(typeof(array1[key] == "object")){
var array2 = array1[key];
for (var key2 in array2){
if(typeof(array2[key2] == "object")){
var array3 = array2[key2];
if(array3[prop] == value){
filtered.push(array3);
}
}
}
}
}
}
return filtered;
}
JsBin example