0

Below if my code

var data = [
{
    'Number': 'B20051209003301',
    'Name': 'GGG'
}, {
    'Number': 'A20051130027901',
    'Name': 'BBB'
}, {
    'Number': 'H20170206000056',
    'Name': 'CCC'
}, {
    'Number': 'K20051216000301',
    'Name': 'AAA'
}, {
    'Number': 'F20170120000056',
    'Name': 'DDD'
}, {
    'Number': 'A20051020032201',
    'Name': 'EEE'
}, {
    'Number': 'A20071005006001',
    'Name': 'AAA'
}, {
    'Number': 'D20170126000023',
    'Name': 'AAA'
}, {
    'Number': 'A20051020016601',
    'Name': 'KKK'
}, {
    'Number': 'A20051028007501',
    'Name': 'LLL'
}
]
var removeUselessData = data;

data.map(function(element, index) {
    if (element['Name'] === "AAA" || Number(element['Number'].slice(1, 5)) < 2011) {
        removeUselessData.splice(index, 1);
    }
});

console.log(removeUselessData);

the result print on my terminal is

[ { Number: 'A20051130027901', Name: 'BBB' },
  { Number: 'H20170206000056', Name: 'CCC' },
  { Number: 'F20170120000056', Name: 'DDD' },
  { Number: 'A20071005006001', Name: 'AAA' },
  { Number: 'A20051020016601', Name: 'KKK' } ]

What I expect it will delete the number small than 2011 and the Name cannot be "AAA".

But the result still have them.

1 Answer 1

2

What you want is Array.filter :

console.log(data.filter(function(element, index){
    return !(element['Name'] === "AAA" || Number(element['Number'].slice(1, 5)) < 2011)
}));

Now, as to why your code isn´t working :

var removeUselessData = data;

Note that this does not copy the data, it justs makes a variable point to the same array reference (if you remove from removeUselessData, you remove from data as well). To prevent this, you need to do :

var removeUselessData = data.slice(0); // this will copy the array (not deep copy though)

Now, when you use splice, you are removing something from the array. Problem is, doing this in a for loop is usually inconsistent, as when you remove something, array elements now have different indexes, so the index from the array and the index from removeUselessData will not match.

To fix it, you could remove the elements in backwards order to ensure consistency :

for (var index = data.length - 1; index >= 0; index--) {
    var element = data[index];
    if (element['Name'] === "AAA" || Number(element['Number'].slice(1, 5)) < 2011) {
        removeUselessData.splice(index, 1);
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.