Delete duplicate letters from multidimensional array in ES6 - javascript

I'm trying to delete duplicate letters in each multidimensional array but am having trouble with the syntax between a single array vs a multidimensional array. I can get it to work for a single array as follows:
function uniq(a) {
return Array.from(new Set(a))
}
// uniq([8,7,8]) successfully returns [8,7]
But it would not work for code like this:
uniq([[8,7,8],[6,8]])
How could this be achieved? Similarly I was trying to make a simple function that just increases the MD array values by 1 but that did not work either:
[[4,6,1],[4,9]].map(function(c,i,a){ return c[i+1] });
There are similar questions like this one, but in my case, each multidimensional array is different, and it's the letters in those MD arrays I want to remove duplicates from. Thanks for any help here.

You can use your existing function and try following.
function uniq(a) {
return Array.from(new Set(a))
}
console.log([[8,7,8],[6,8]].map(uniq));
Similarly, for the addition by 1, you can try following
console.log([[4,6,1],[4,9]].map(a => a.map(v => v+1)));

let arrayWithUnique1DArray = [[4,6,4],[4,9,9]].map((item)=>{
return [...(new Set(item))]
});
console.log(arrayWithUnique1DArray)
function increaseEachValueBy({arrays, value}={}){
arrays.forEach((array, index, original)=> { original[index] = array.map(item => item+ value)})
}
let TwoDimensionArray = [[4,6,4],[4,9,9]]
increaseEachValueBy({ arrays: TwoDimensionArray , value:10})
console.log(TwoDimensionArray)

Related

How to omit a particular key while pushing json objects to an array?

So, I have a JSON array of objects , which in turn contains other arrays of objects. This array of objects has no particular fixed structure as such so its very difficult for me do something like delete mainArray[0].obj.subobj[1].objToOmit;
So I have a key/object called possibleAnswers which I need to remove/omit. In my program I am pushing the contents of one array into another array. So while I am pushing the contents of first array of objects into another, I need to omit the possibleAnswers object from being pushed.
Is there any way or function that searches an array of objects and helps me omit the necessary key? Or what would be a solution as per your thoughts?
Example :
Here is a minimal example: https://codebeautify.org/jsonviewer/cb9fea0d
Edit: In the above JSON there is a key called possibleMembers which is wrong. its possibleAnswers
var collectObservationsFromConceptSets = function () {
$scope.consultation.observations = [];
_.each($scope.consultation.selectedObsTemplates, function (conceptSetSection) {
if (conceptSetSection.observations) {
_.each(conceptSetSection.observations, function (obs) {
$scope.consultation.observations.push(obs);
});
}
});
}
In the above code while pushing the object into another array, how can I omit the possibleAnswers keys? Is there a way to omit?
Thanks a lot people! Both the answers are correct and have generated the exact correct output. Unfortunately I can only select 1 answer as correct and its going to be random.
This is a recursive omit that uses _.transform() to iterate and ignore one or more keys in an array:
const omitRecursive = (keys, obj) => _.transform(obj, (acc, v, k) => {
// if key is view, and it and has an id value replace it with equivalent from views
if(keys.includes(k)) return;
acc[k] = _.isObject(v) ? omitRecursive(keys, v) : v;
});
const data = [{"observations":[{"possibleAnswers":[],"groupMembers":[{"possibleAnswers":[]},{"groupMembers":[{"possibleMembers":[]},{"possibleMembers":[]}]}]}]},{"observations":"Same as above"},{"observations":"Same as above"}];
const result = omitRecursive(['possibleAnswers'], data);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
This function will remove all 'possibleAnswers' if called on your original array like removeKey(arr, 'possibleAnswers')
function removeKey(objOrArr, keyToRemove) {
if (Array.isArray(objOrArr)) {
objOrArr.forEach(o => removeKey(o, keyToRemove));
} else if (typeof objOrArr === 'object') {
delete objOrArr[keyToRemove];
Object.values(objOrArr).forEach(v => removeKey(v, keyToRemove));
}
}

trying to push each element with comma separated values also as an array element

I have the below json object.
$scope.myDataList = [
{name:"one,two"},
{name:"three"},
{name:"four"},
{name:"five,eight,nine"}
]
I'm iterating the list and push the elements in the array as shown below.
$scope.myArray = new Array();
angular.forEach($scope.myDataList, function (value, key) {
$scope.myArray.push(value.name);
});
I want to push each element with comma spearated values also in the array.
example:
When I print $scope.myArray[0], it prints one,two.
But expected result is I want to print one for
$scope.myArray[0] and two for $scope.myArray[1], three for $scope.myArray[2].
Each value with comma separation also I want to push as an array element.
I tried as below but does not work.
var array = $scope.myArray.split(',');
Demo: http://plnkr.co/edit/q36BQeqsj5GVNkP4PPhq?p=preview
You need to split the name and concatenate the result to the array instead:
angular.forEach($scope.myDataList, function (value, key) {
$scope.myArray = $scope.myArray.concat(value.name.split(','));
});
Your problem has nothing to do with AngularJS, so I rewrote it in plain JavaScript:
$scope = {};
$scope.myDataList = [{name:"one,two"},{name:"three"},{name:"four"},{name:"five,eight,nine"}]
$scope.myArray = $scope.myDataList.map(({ name }) => name.split(','))
.reduce((result, splitElement) => result.concat(splitElement), []);
console.log($scope.myArray);
Note that the following line in your code
$scope.myArray.push(value.name);
pushes unsplit strings like 'five,eight,nine' into $scope.myArray. This is not what you want. Also, $scope.myArray.split(',') will fail, since Array.prototype has no split function.
One way to achieve the correct result is to map over the original array and split every element (the result is an array of string arrays). After that, you can join the inner string arrays together using Array.concat. This is what the following two lines do:
$scope.myArray = $scope.myDataList.map(({ name }) => name.split(','))
.reduce((result, splitElement) => result.concat(splitElement), []);
Here's a fairly simple means:
$scope.myArray = $scope.myDataList.reduce((a, {name}) => a.concat(name.split(',')), [])
Note that what you're trying to do is take the orginal list and create a new one. Since it's not a one-for-one mapping, it's not map. But reduce is appropriate, and carries more information than forEach.
const $scope = {
myDataList: [
{name:"one,two"},
{name:"three"},
{name:"four"},
{name:"five,eight,nine"}
]
}
$scope.myArray = $scope.myDataList.reduce((a, {name}) => a.concat(name.split(',')), [])
console.log($scope)
while pushing the array element you can do:
$scope.myArray = $scope.myArray.concat(value.name.split(","));
Here is the code to try.
http://plnkr.co/edit/nc91XI4vPJT0nEZvmMzU?p=preview

Pass array of objects by reference and save the actual array in JavaScript

I am passing an array to a function. Since, in javascript,
arrays by default get passed by reference I tried to make a copy of array. But in the end, the operations performed in function effects the actual array data.
All I want to do is save the actual state of an array.
Here is my code :
let arrcopy =new Array( items.dt);
citem = binarySearch(arrcopy[0], ind.ItemID);
You means you want to preserve the original array as it is (you want to preserve immutability)?
Then use reduce method.
const test = (arr) => {
return arr.reduce((result, val) => {
// do the needful here
result.push(val);
return result;
}, []);
}
expect(arr).to.be.equal(result); => will return false as the original array won't be updated
You will need to create array as copy with Object.assign
let arrcopy = Object.assign([],items.dt);
citem = binarySearch(arrcopy[0], ind.ItemID);
Or just ES6 way with destruction/spread operator is enough
let arrcopy = [...items.dt];
JSON.parse(JSON.stingify(items.dt))
this has made my work

Chaining methods on array display as undefined [duplicate]

This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 5 years ago.
const array = new Array(9).fill([]).forEach(function(value, index, arr) {
arr[index] = Array(9).fill(0);
console.log(index, arr[index]); // This line report properly by creating
}); // new array.
console.log(array); // Reported as underdefined.
However, if redefine as below, it works as expected.
const array = new Array(9).fill([]);
array.forEach( function(value,index,arr){
arr[index] = Array(9).fill(0);
console.log(index,arr[index]);
});
console.log(array);
I would like to define multiple dimensional arrays within one line used as this state command.
But what is the problem for scenario 1 where bounded forEach methods array definitions work fine?
But what is the problem for scenario 1 where bounded forEach methods
array defnitions works fine.
Problem is forEach returns undefined
I woule like to define multiple dimensional arrays within one line
used as this.state command.
You can use map for the same
var output = new Array(9).fill([]).map( function(value,index,arr){
return Array(9).fill(0); //return the inner array
});
Or as #bergi suggested, you can use Array.from as well
var output = Array.from(Array(9)).map( function(value,index,arr){
return Array(9).fill(0);
});
As other answers have already mentioned Array.forEach returns undefined or does not return anything, you cannot use it.
As an alternate approach, you can use Array.from.
Following is a sample:
var output = Array.from({
length: 9
}, () => {
return Array.from({
length: 9
}, () => 0)
});
console.log(output)
Also, one more issue with your code is, you are using an object in Array.fill. What array.fill does is, it will create the value to be filled first and then fill it in all items.
var output = new Array(9).fill([]);
output[0].push(1);
console.log(output)
In you check the output, it says /**ref:2**/, but if you check in console, you will notice that all items will have item 1. So you should avoid using objects with Array.fill.
You want to generate array of 9 arrays filled with 0 and return it to variable.
You can achieve this using map method.
const array =
new Array(9)
.fill([])
.map(function(){
return Array(9).fill(0);
});
console.log(array);
p.s. no value, index and etc needed to pass to map methods argument in Your case
Array.prototype.forEach returns undefined. Just call the forEach like below.
const array = new Array(9).fill([])
array.forEach( function(value,index,arr){
arr[index] = Array(9).fill(0);
});
// [
// [0, 0, 0, ...],
// ...
// ]
Using map would be another choice, but I don't vote for it because it creates yet another array in memory.

Javascript: return the first value from arrays within an object

I am working on a javascript homework problem and am a bit stuck:
Create a function called getFirstAnimals that returns an array of all the first animals in the object.
Example: [‘bears’,’penguins’,panther’,’flea’]
I scripted the following function:
var animals = {
mammals:['bears','lions','whales','otters'],
birds:['penguins','ducks','swans','chickens'],
cats:['panther','mountain lion','leopard','snow tiger'],
insects: ['flea','mosquito','beetle','fly','grasshopper']
}
function getFirstAnimals(array) {
var firstAnimals = [];
for (key in array) {
firstAnimals.push(array[key].slice(0,1))
}
return firstAnimals;
}
console.log(getFirstAnimals(animals));
my problem is that the output I am generating is an array of arrays made up of the first animals, [Array[1], Array[1], Array[1], Array[1]], and not the strings, [‘bears’,’penguins’,panther’,’flea’]. Any suggestions on how to get the desired output is much appreciated.
Instead of pushing array[key].slice(0,1) you need to push array[key][0], where [0] is getting you the first item in the array.
You can use
firstAnimals.push(array[key][0])
for that. It gets the first element from the array
Yet another approach
var animals = {
mammals:['bears','lions','whales','otters'],
birds:['penguins','ducks','swans','chickens'],
cats:['panther','mountain lion','leopard','snow tiger'],
insects: ['flea','mosquito','beetle','fly','grasshopper']
}
function getFirstAnimals(array) {
return Object.keys(array).map(v => array[v][0]);
}
console.log(getFirstAnimals(animals));
A oneliner: console.log(animals[Object.keys(animals)[0]]);

Categories

Resources