Manipulating array in javascript by slicing - javascript

I have an array of twelve items :
var arrToIterate = [];
arrToIterate = //Data from service to populate;
Each item in the array has two fields : Name and title.
If suppose the array has Names as :
Scenario 1:
[0]: Name: Iron
[1]: Name: Steel
[2]: Name: ContainsIron
[3]: Name: ContainsSteel
[4]: Name : Manganese
[5]: Name: Magnesium
I need the ouput as :
[0]: Name: Iron
[1]: Name: Steel
[2]: Name : Manganese
[3]: Name: Magnesium
Scenario 2:
If suppose the array has Names as :
[0]: Name: Iron
[1]: Name: Steel
[2]: Name : Manganese
[3]: Name: Magnesium
I need the output as:
[0]: Name: Manganese
[1]: Name: Magnesium
I am trying to do in this way :
$.each(arrToIterate, function (element, index, arr) {
if (element.Name == "ContainsIron" || element.Name == "ContainsSteel") {
arr.splice(index, 1);
}
});
But I am not getting the handle the second scenario . How do I achieve array manipulation for both the scenarios?
Edit :
If the array contains "ContainsIron" , then ContainsIron needs to be removed ,similarly if it contains ContainsSteel , then ContainsSteel needs to be removed.
Else
If array doesnt contain ContainsSteel , then Steel needs to be removed .
If array doesnt contain ContainsIron, then Iron needs to be removed .

Here's a simple version. First, you'll want to make a remove function which removes something if it's in there, and a function which removes a named metal:
function removeIfExists(arr,name){
// get the index of the entry:
for(var i in arr){
if(arr[i].Name==name){
// Got it! Rip it out:
arr.splice(i,1);
return true;
}
}
// Not in the array at all.
return false;
}
// Removes a metal from the given array
function removeMetal(arr,name){
// Try removing e.g. ContainsIron:
if(!removeIfExists(arr,"Contains"+name)){
// ContainsIron/ ContainsSteel wasn't in there. Try removing 'Iron'/ 'Steel':
removeIfExists(arr,name);
}
}
That leaves the usage as just:
removeMetal(arrToIterate,"Iron");
removeMetal(arrToIterate,"Steel");
Here it is as a fiddle

You can just use vanilla Javascript to do this, using the filter function:
var arrToIterate = [{
name: 'Iron'
}, {
name: 'Iron'
}, {
name: 'Iron'
}, {
name: 'Manganese'
}, {
name: 'Iron'
}, {
name: 'Iron'
}, {
name: 'Iron'
}, {
name: 'ContainsSteel'
}];
filterArray(arrToIterate);
function filterArray(arrToIterate) {
var containsSteel = false,
containsIron = false,
filteredArray;
arrToIterate.forEach(function(item) {
(item.name === 'ContainsSteel') ? containsSteel = true: null;
(item.name === 'ContainsIron') ? containsIron = true: null;
});
console.log("Original Array");
console.log(arrToIterate);
console.log("ContainsSteel " + containsSteel);
console.log("ContainsIron " + containsIron);
if (containsSteel) {
filteredArray = arrToIterate.filter(function(item) {
return !(item.name === 'ContainsSteel');
});
}
if (containsIron) {
filteredArray = filteredArray.filter(function(item) {
return !(item.name === 'ContainsIron');
});
}
if (!(containsIron)) {
filteredArray = filteredArray.filter(function(item) {
return !(item.name === 'iron');
})
}
if (!(containsSteel)) {
filteredArray = filteredArray.filter(function(item) {
return !(item.name === 'Steel');
})
}
console.log("Filtered array ");
console.log(filteredArray);
return filteredArray;
};

Because of the lack of consistency of the "Contain" rules (Manganese for example, doesn't have them), we need to define a hash of what won't be displayed if there isn't a contain rule for it.
Afterwards we can scan the array for for "Contain" rules update the hash, and then just filter array accordingly.
var arrToIterate = [
{ Name: 'Iron' },
{ Name: 'Steel' },
{ Name: 'ContainsIron' },
{ Name: 'Manganese' },
{ Name: 'Magnesium' }
];
var result = arrToIterate.filter(function(metal) {
return metal.Name in this ? this[metal.Name] : true; // if there's an entry in the hash (this) use it. If not keep the item.
}, arrToIterate.reduce(function(hash, metal) { // create the hash
if(metal.Name.indexOf('Contains') !== -1) { // if there's a contain rule
hash[metal.Name] = false; // remove the rule
hash[metal.Name.replace('Contains', '')] = true; // show the metal
}
return hash;
}, { Iron: false, Steel: false })) // the baseline is false for every metal with a Contain rule
console.log(result);

If you just want to filter the array you can use filter:
var array = [
{ name: 'Iron'},
{ name: 'Steel'},
{ name: 'Manganese'},
{ name: 'Magnesium'}
];
var filtered = array.filter(function(item) {
return item.name === 'Iron';
})
Not sure what your selection criteria is, but you just need to define these in the body of the filter callback.
Edit
I see you updated your criteria - so you would just have to amend the filter callback accordingly as I think other responders have now indicated.

Related

How to access an array of objects which is a key-value pair

i want to access the id 'qwsa221' without using array index but am only able to reach and output all of the array elements not a specific element.
i have tried using filter but couldnt figure out how to use it properly.
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Use Object.keys() to get all the keys of the object and check the values in the array elements using . notation
let lists = {
def453ed: [{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Object.keys(lists).forEach(function(e) {
lists[e].forEach(function(x) {
if (x.id == 'qwsa221')
console.log(x)
})
})
You can use Object.Keys method to iterate through all of the keys present.
You can also use filter, if there are multiple existence of id qwsa221
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
let l = Object.keys(lists)
.map(d => lists[d]
.find(el => el.id === "qwsa221"))
console.log(l)
you can do it like this, using find
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
console.log(
lists.def453ed // first get the array
.find( // find return the first entry where the callback returns true
el => el.id === "qwsa221"
)
)
here's a corrected version of your filter :
let lists = {def453ed: [{id: "qwsa221",name: "Mind"},{id: "jwkh245",name: "Space"}]};
// what you've done
const badResult = lists.def453ed.filter(id => id === "qwsa221");
/*
here id is the whole object
{
id: "qwsa221",
name: "Mind"
}
*/
console.log(badResult)
// the correct way
const goodResult = lists.def453ed.filter(el => el.id === "qwsa221");
console.log(goodResult)
// filter returns an array so you need to actually get the first entry
console.log(goodResult[0])

splice is not removing the first index from array of objects

I have two arrays of objects and I want to compare the objects of the first array to the ones of the second array. If they match, I use the splice to remove the object from the second array.
I have the following code
existing.forEach((existingitem, existingindex, existingfeatures) => {
(newdatafeat.features).forEach((newitem, newindex, newfeatures) => {
console.log('existing index-name --- new index-name', existingindex ,' - ',existingitem.values_.name,' - ',newindex,' - ',newitem.properties.name,'-----');
if (existingitem.values_.id == newitem.properties.id && existingitem.values_.cat == newitem.properties.cat){
console.log(' index to remove - ', newindex); (newdatafeat.features).splice(newindex,1);
}
})
});
So, If existing is
var existing= [
{ info: true, values_:{id:1, cat:true, name : "John"} },
{ info : true, values_:{id:2, cat:false, name : "Alice"} }
];
and newdatafeat.features is
var newdatafeat= {
status:scanned,
features : [ { info: true, properties:{id:1, cat:true, name : "Mike"} },
{ info : false, properties:{id:22, cat:false,name : "Jenny"} } ]
};
Then, Mike from newdatafeat.features should be removed.
The error is that every item of the newdatafeat.features array with index 0 is not removed. In the loop, I can see index to remove - 0, but Mike is never removed. I know, because if I console.log the newdatafeat.features after the loops, Mike is there
This is inside an angular6 code.
What am I missing here?
Thanks
I had to clean up some code, but it looks like yours is working fine. It identified one element to be removed, called slice and it was gone.
var existing = [{
info: true,
values_: {
id: 1,
cat: true,
name: "John"
}
},
{
info: true,
values_: {
id: 2,
cat: false,
name: "Alice"
}
}
];
var newdata = {
status: "scanned",
features: [
{
info: true,
properties: {
id: 1,
cat: true,
name: "Mike"
}
},
{
info: false,
properties: {
id: 22,
cat: false,
name: "Jenny"
}
}
]
};
existing.forEach(
(existingitem, existingindex, existingfeatures) => {
(newdata.features).forEach((newitem, newindex, newfeatures) => {
console.log('existing index-name --- new index-name', existingindex, ' - ', existingitem.values_.name, ' - ', newindex, ' - ', newitem.properties.name, '-----');
if (existingitem.values_.id == newitem.properties.id && existingitem.values_.cat == newitem.properties.cat) {
console.log(' index to remove - ', newindex);
(newdata.features).splice(newindex, 1);
}
})
});
console.log(newdata.features);
The main problem here is that you are iterating an array in a loop, but you are removing items from that array in the same loop. So the index will often be off, and the wrong element or no element will be removed. It can be hard to reproduce with simple examples, but here ya go:
function removeVowels(letters) {
letters.forEach((element, index, arr) => {
if ('aeiou'.indexOf(element) > -1) {
arr.splice(index, 1);
}
});
}
var myArray = ['a','b','c','d','e'];
removeVowels(myArray);
console.log(myArray);
// works great!
var myArray = ['a','e','c','d','b'];
removeVowels(myArray);
console.log(myArray);
// wtf!
A simple way to approach this problem is to handle the looping manually, and change the index manually if you DO remove an element.
function removeVowels(letters) {
for (var i=0; i < letters.length; i++) {
if ('aeiou'.indexOf(letters[i]) > -1) {
letters.splice(i, 1);
i--;
}
}
}
var myArray = ['a','b','c','d','e'];
removeVowels(myArray);
console.log(myArray);
// works great!
var myArray = ['a','e','c','d','b'];
removeVowels(myArray);
console.log(myArray);
// hurray!

Find Duplicate Array By Caption without using multiple loops [duplicate]

I need some help with iterating through array, I keep getting stuck or reinventing the wheel.
values = [
{ name: 'someName1' },
{ name: 'someName2' },
{ name: 'someName1' },
{ name: 'someName1' }
]
How could I check if there are two (or more) same name value in array? I do not need a counter, just setting some variable if array values are not unique. Have in mind that array length is dynamic, also array values.
Use array.prototype.map and array.prototype.some:
var values = [
{ name: 'someName1' },
{ name: 'someName2' },
{ name: 'someName4' },
{ name: 'someName2' }
];
var valueArr = values.map(function(item){ return item.name });
var isDuplicate = valueArr.some(function(item, idx){
return valueArr.indexOf(item) != idx
});
console.log(isDuplicate);
ECMA Script 6 Version
If you are in an environment which supports ECMA Script 6's Set, then you can use Array.prototype.some and a Set object, like this
let seen = new Set();
var hasDuplicates = values.some(function(currentObject) {
return seen.size === seen.add(currentObject.name).size;
});
Here, we insert each and every object's name into the Set and we check if the size before and after adding are the same. This works because Set.size returns a number based on unique data (set only adds entries if the data is unique). If/when you have duplicate names, the size won't increase (because the data won't be unique) which means that we would have already seen the current name and it will return true.
ECMA Script 5 Version
If you don't have Set support, then you can use a normal JavaScript object itself, like this
var seen = {};
var hasDuplicates = values.some(function(currentObject) {
if (seen.hasOwnProperty(currentObject.name)) {
// Current name is already seen
return true;
}
// Current name is being seen for the first time
return (seen[currentObject.name] = false);
});
The same can be written succinctly, like this
var seen = {};
var hasDuplicates = values.some(function (currentObject) {
return seen.hasOwnProperty(currentObject.name)
|| (seen[currentObject.name] = false);
});
Note: In both the cases, we use Array.prototype.some because it will short-circuit. The moment it gets a truthy value from the function, it will return true immediately, it will not process rest of the elements.
In TS and ES6 you can create a new Set with the property to be unique and compare it's size to the original array.
const values = [
{ name: 'someName1' },
{ name: 'someName2' },
{ name: 'someName3' },
{ name: 'someName1' }
]
const uniqueValues = new Set(values.map(v => v.name));
if (uniqueValues.size < values.length) {
console.log('duplicates found')
}
To know if simple array has duplicates we can compare first and last indexes of the same value:
The function:
var hasDupsSimple = function(array) {
return array.some(function(value) { // .some will break as soon as duplicate found (no need to itterate over all array)
return array.indexOf(value) !== array.lastIndexOf(value); // comparing first and last indexes of the same value
})
}
Tests:
hasDupsSimple([1,2,3,4,2,7])
// => true
hasDupsSimple([1,2,3,4,8,7])
// => false
hasDupsSimple([1,"hello",3,"bye","hello",7])
// => true
For an array of objects we need to convert the objects values to a simple array first:
Converting array of objects to the simple array with map:
var hasDupsObjects = function(array) {
return array.map(function(value) {
return value.suit + value.rank
}).some(function(value, index, array) {
return array.indexOf(value) !== array.lastIndexOf(value);
})
}
Tests:
var cardHand = [
{ "suit":"spades", "rank":"ten" },
{ "suit":"diamonds", "rank":"ace" },
{ "suit":"hearts", "rank":"ten" },
{ "suit":"clubs", "rank":"two" },
{ "suit":"spades", "rank":"three" },
]
hasDupsObjects(cardHand);
// => false
var cardHand2 = [
{ "suit":"spades", "rank":"ten" },
{ "suit":"diamonds", "rank":"ace" },
{ "suit":"hearts", "rank":"ten" },
{ "suit":"clubs", "rank":"two" },
{ "suit":"spades", "rank":"ten" },
]
hasDupsObjects(cardHand2);
// => true
if you are looking for a boolean, the quickest way would be
var values = [
{ name: 'someName1' },
{ name: 'someName2' },
{ name: 'someName1' },
{ name: 'someName1' }
]
// solution
var hasDuplicate = false;
values.map(v => v.name).sort().sort((a, b) => {
if (a === b) hasDuplicate = true
})
console.log('hasDuplicate', hasDuplicate)
const values = [
{ name: 'someName1' },
{ name: 'someName2' },
{ name: 'someName4' },
{ name: 'someName4' }
];
const foundDuplicateName = values.find((nnn, index) =>{
return values.find((x, ind)=> x.name === nnn.name && index !== ind )
})
console.log(foundDuplicateName)
Found the first one duplicate name
const values = [
{ name: 'someName1' },
{ name: 'someName2' },
{ name: 'someName4' },
{ name: 'someName4' }
];
const foundDuplicateName = values.find((nnn, index) =>{
return values.find((x, ind)=> x.name === nnn.name && index !== ind )
})
You just need one line of code.
var values = [
{ name: 'someName1' },
{ name: 'someName2' },
{ name: 'someName4' },
{ name: 'someName2' }
];
let hasDuplicates = values.map(v => v.name).length > new Set(values.map(v => v.name)).size ? true : false;
Try an simple loop:
var repeat = [], tmp, i = 0;
while(i < values.length){
repeat.indexOf(tmp = values[i++].name) > -1 ? values.pop(i--) : repeat.push(tmp)
}
Demo
With Underscore.js A few ways with Underscore can be done. Here is one of them. Checking if the array is already unique.
function isNameUnique(values){
return _.uniq(values, function(v){ return v.name }).length == values.length
}
With vanilla JavaScript
By checking if there is no recurring names in the array.
function isNameUnique(values){
var names = values.map(function(v){ return v.name });
return !names.some(function(v){
return names.filter(function(w){ return w==v }).length>1
});
}
//checking duplicate elements in an array
var arr=[1,3,4,6,8,9,1,3,4,7];
var hp=new Map();
console.log(arr.sort());
var freq=0;
for(var i=1;i<arr.length;i++){
// console.log(arr[i-1]+" "+arr[i]);
if(arr[i]==arr[i-1]){
freq++;
}
else{
hp.set(arr[i-1],freq+1);
freq=0;
}
}
console.log(hp);
You can use map to return just the name, and then use this forEach trick to check if it exists at least twice:
var areAnyDuplicates = false;
values.map(function(obj) {
return obj.name;
}).forEach(function (element, index, arr) {
if (arr.indexOf(element) !== index) {
areAnyDuplicates = true;
}
});
Fiddle
Adding updated es6 function to check for unique and duplicate values in array. This function is modular and can be reused throughout the code base. Thanks to all the post above.
/* checks for unique keynames in array */
const checkForUnique = (arrToCheck, keyName) => {
/* make set to remove duplicates and compare to */
const uniqueValues = [...new Set(arrToCheck.map(v => v[keyName]))];
if(arrToCheck.length !== uniqueValues.length){
console.log('NOT UNIQUE')
return false
}
return true
}
let arr = [{name:'joshua'},{name:'tony'},{name:'joshua'}]
/* call function with arr and key to check for */
let isUnique = checkForUnique(arr,'name')
checkDuplicate(arr, item) {
const uniqueValues = new Set(arr.map((v) => v[item]));
return uniqueValues.size < arr.length;
},
console.log(this.checkDuplicate(this.dutyExemptionBase, 'CI_ExemptionType')); // true || false
It is quite interesting to work with arrays
You can use new Set() method to find duplicate values!
let's assume you have an array of objects like this...
let myArray = [
{ id: 0, name: "Jhon" },
{ id: 1, name: "sara" },
{ id: 2, name: "pop" },
{ id: 3, name: "sara" }
]
const findUnique = new Set(myArray.map(x => {
return x.name
}))
if(findUnique.size < myArray.length){
console.log("duplicates found!")
}else{
console.log("Done!")
}
const duplicateValues = [{ name: "abc" }, { name: "bcv" }, { name: "abc" }];
const isContainDuplicate = (params) => {
const removedDuplicate = new Set(params.map((el) => el.name));
return params.length !== removedDuplicate.size;
};
const isDuplicate = isContainDuplicate(duplicateValues);
console.log("isDuplicate");

how to use .include() method to check the value which is in a json inside array

I want to compare the value of a particular key in my JSON array with new value to check whether the value exists or not.
For example, I have an array:
[
{ name: abc, num: 121212 },
{ name: bcd, num: 21212 },
{ name: def, num: 111222 }
]
Now a new value comes which I want to check. Does that name already exist? If it does, then I only want to update the number and if not then I want to push the object in the array.
Here is my code:
if ((Dnum.num).includes(number)) {
console.log("inside if");
console.log(Dnum.indexOf(number));
} else {
Dnum.push({num:number,
lat:lat,
lng:lng,
name:name
});
}
Well, your problem (if I understand correctly) is that you want to use includes() but what you actually want to accomplish doesn't correspond to what the method does. You want to find if there's an object with a certain name in your array already, not if it contains a known element. Something like this:
var data = [{name: 'abc', num: 121212}, {name: 'bcd', num: 21212}, {name: 'def', num: 111222}];
function addOrUpdate(newElement, data) {
var i;
for (i = 0; i < data.length; i++) {
if (data[i].name == newElement.name) {
data[i] = newElement;
return;
}
}
data.push(newElement);
}
addOrUpdate({name: 'bcd', num: 131313}, data);
console.log(data);
addOrUpdate({name: 'new', num: 131313}, data);
console.log(data);
Problem:
Actually .includes() and .indexOf() methods won't work with objects, they should be used with an array of strings or Numbers as they use strict equality to compare the elements and objects can't be compared this way, so you need to implement this logic by yourself.
Solution:
You need to check if an object matching the searched name already exists in the array, update the num value of this object, otherwise if no object matches the searched name, push the new object to the array:
if (arr.some(function(obj) {
return obj.name === searchedVal.name;
})) {
arr.forEach(function(el, index) {
if (el.name === searchedVal.name) {
el.num += searchedVal.num;
found = true;
}
});
} else {
arr.push(searchedVal);
}
Demo:
var arr = [{
name: "abc",
num: 121212
}, {
name: "bcd",
num: 21212
}, {
name: "def",
num: 111222
}];
var searchedVal = {
name: "abc",
num: 5
};
if (arr.some(function(obj) {
return obj.name === searchedVal.name;
})) {
arr.forEach(function(el, index) {
if (el.name === searchedVal.name) {
el.num += searchedVal.num;
found = true;
}
});
} else {
arr.push(searchedVal);
}
console.log(arr);
If you don't want to use .some() method, you can do it this way:
var searchedVal = {
name: "abc",
num: 5
};
var found = false;
arr.forEach(function(el, index) {
if (el.name === searchedVal.name) {
el.num+= searchedVal.num;
found = true;
}
});
if (!found) {
arr.push(searchedVal);
}
Use Array.prototype.find():
var res = Dnum.find(function (item) {
return item.num === number;
});
if (res) {
console.log("inside if");
console.log(res);
res.num = number;
} else {
Dnum.push({
num:number,
lat:lat,
lng:lng,
name:name
});
}

New array of objects by comparing and pushing unique objects

I have 2 arrays of objects exclude and people, I want to create a new object by checking exclude properties against people properties and only adding objects in people that don't feature in exclude. So far my attempt is a little wild and wondering if someone can help make things a little better or offer a nicer solution?
Fiddle http://jsfiddle.net/kyllle/k02jw2j0/
JS
var exclude = [{
id: 1,
name: 'John'
}];
var peopleArr = [{
id: 1,
name: 'John'
}, {
id: 2,
name: 'James'
}, {
id: 3,
name: 'Simon'
}];
var myObj = [];
for (key in peopleArr) {
for (k in exclude) {
if (JSON.stringify(peopleArr[key]) != JSON.stringify(exclude[k])) {
console.log(peopleArr[key]);
myObj.push(peopleArr[key]);
}
}
}
console.log(myObj);
Under the assumption that exclude can have multiple items, I would use a combination of filter() and forEach() :
var newArray = peopleArr.filter(function(person) {
include = true;
exclude.forEach(function(exl) {
if (JSON.stringify(exl) == JSON.stringify(person)) {
include = false;
return;
}
})
if (include) return person;
})
forked fiddle -> http://jsfiddle.net/6c24rte8/
You repeat some JSON.stringify calls.
You can convert your arrays to JSON once, and then reuse it. Also, you can replace your push by Array.prototype.filter.
var excludeJson = exclude.map(JSON.stringify);
peopleArr = peopleArr.filter(function(x) {
return excludeJson.indexOf(JSON.stringify(x)) === -1;
});
Here is the working snippet:
var exclude = [{
id: 1,
name: 'John'
}];
var peopleArr = [{
id: 1,
name: 'John'
}, {
id: 2,
name: 'James'
}, {
id: 3,
name: 'Simon'
}];
var excludeJson = exclude.map(JSON.stringify);
peopleArr = peopleArr.filter(function(x) {
return excludeJson.indexOf(JSON.stringify(x)) === -1;
});
document.body.innerText = JSON.stringify(peopleArr);
This can be achieved with .filter and .findIndex
var myObj = peopleArr.filter(function(person){
var idx = exclude.findIndex(function(exc) { return person.id == exc.id && person.name == exc.name; });
return idx == -1; // means current person not found in the exclude list
});
I have explicitly compared the actual properties back to the original, there is nothing particularly wrong with your original way of comparing the stringified version (JSON.stringify(e) == JSON.stringify(x) could be used in my example)

Categories